package paymentconfig

import (
	"context"
	"errors"
	"time"

	"hfb_sys/backend/internal/model"

	"gorm.io/gorm"
)

// IncrementUsage 增加使用统计
func (r *Repository) IncrementUsage(ctx context.Context, id uint64, amountCent int64) error {
	now := time.Now()
	return r.db.WithContext(ctx).Model(&model.PaymentMerchantConfig{}).Where("id = ?", id).Updates(map[string]any{
		"total_transactions": gorm.Expr("total_transactions + ?", 1),
		"total_amount_cent":  gorm.Expr("total_amount_cent + ?", amountCent),
		"last_used_at":       now,
	}).Error
}

// RecordUsage 记录支付配置命中情况，同一个支付单只记录一次。

// RecordUsage 记录支付配置命中情况，同一个支付单只记录一次。
func (r *Repository) RecordUsage(ctx context.Context, configID uint64, paymentOrderID uint64, provider string, merchantID string, amountCent int64, bizType string) error {
	if configID == 0 || paymentOrderID == 0 {
		return nil
	}
	return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		var existing model.PaymentConfigUsageLog
		err := tx.Where("payment_order_id = ?", paymentOrderID).First(&existing).Error
		if err == nil {
			return nil
		}
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return err
		}
		log := model.PaymentConfigUsageLog{
			ConfigID:       configID,
			PaymentOrderID: paymentOrderID,
			Provider:       provider,
			MerchantID:     merchantID,
			AmountCent:     amountCent,
			BizType:        bizType,
		}
		if err := tx.Create(&log).Error; err != nil {
			return err
		}
		now := time.Now()
		return tx.Model(&model.PaymentMerchantConfig{}).Where("id = ?", configID).Updates(map[string]any{
			"total_transactions": gorm.Expr("total_transactions + ?", 1),
			"total_amount_cent":  gorm.Expr("total_amount_cent + ?", amountCent),
			"last_used_at":       now,
		}).Error
	})
}

// deactivateOtherConfigs 保证全局同一时间只有一个启用配置。
