package mysql

import (
	"context"
	"fmt"
	"strings"

	"gorm.io/gorm"

	"data-platform/model"
)

type ARTable struct {
	db *gorm.DB
}

type ARTableResult struct {
	model.ARTable
	StripeInvoices *string `gorm:"column:stripe_invoices"`
}

func newARTable(ds *datastore) *ARTable {
	return &ARTable{db: ds.db}
}

func (a *ARTable) ListByMonth(_ context.Context, billMonth string) (records []model.ARTable, err error) {
	// 使用子查询先将 stripe_invoice 聚合成数组
	subQuery := a.db.Table("ar_stripe_invoice").
		Select("tenant_id, bill_month, GROUP_CONCAT(stripe_invoice) as stripe_invoices").
		Where("bill_month = ?", billMonth).
		Group("tenant_id, bill_month")

	// 使用临时结构体接收查询结果
	var tempResults []ARTableResult

	// 主查询左连接子查询结果
	err = a.db.Table("ar_table as ar").
		Select("ar.*, sub.stripe_invoices").
		Joins("LEFT JOIN (?) as sub ON ar.tenant_id = sub.tenant_id AND ar.bill_month = sub.bill_month", subQuery).
		Where("ar.bill_month = ?", billMonth).
		Find(&tempResults).Error

	if err != nil {
		return nil, err
	}

	// 将临时结果转换为最终结果
	records = make([]model.ARTable, len(tempResults))
	for i, temp := range tempResults {
		records[i] = temp.ARTable
		if temp.StripeInvoices != nil {
			// 将逗号分隔的字符串转换为数组格式的字符串
			invoices := strings.Split(*temp.StripeInvoices, ",")
			// 过滤空值
			var filteredInvoices []string
			for _, inv := range invoices {
				if strings.TrimSpace(inv) != "" {
					filteredInvoices = append(filteredInvoices, fmt.Sprintf(`"%s"`, strings.TrimSpace(inv)))
				}
			}
			if len(filteredInvoices) > 0 {
				arrayStr := "[" + strings.Join(filteredInvoices, ",") + "]"
				records[i].StripeInvoice = &arrayStr
			}
		}
	}

	return records, nil
}

func (a *ARTable) DeleteAndCreate(_ context.Context, records []model.ARTable, arStripe []model.ARStripeInvoice, billMonth string) (err error) {
	// 开启事务
	tx := a.db.Begin()
	if tx.Error != nil {
		return tx.Error
	}

	// 确保事务最终会被处理
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 删除旧的 ARTable 记录
	if err := tx.Where("bill_month = ?", billMonth).Unscoped().Delete(&model.ARTable{}).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 删除旧的 ARStripeInvoice 记录
	if err := tx.Where("bill_month = ?", billMonth).Unscoped().Delete(&model.ARStripeInvoice{}).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 创建新的 ARTable 记录
	if err := tx.Create(&records).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 创建新的 ARStripeInvoice 记录
	if len(arStripe) > 0 {
		if err := tx.Create(&arStripe).Error; err != nil {
			tx.Rollback()
			return err
		}
	}

	// 提交事务
	return tx.Commit().Error
}
