package mysql

import (
	"context"
	"database/sql"
	"time"

	"hyapp/pkg/appcode"
)

// luckyGiftRechargeSnapshot 是 wallet 在送礼交易内固化给 lucky-gift 的充值画像。
// 它只按单个用户的 (app_code,user_id,created_at_ms) 索引读取最近 30 个 UTC 自然日，
// 不扫描全站充值流水；快照写进 gift transaction metadata 后，幂等重放永远返回首次结果。
type luckyGiftRechargeSnapshot struct {
	SevenDayCoins  int64
	ThirtyDayCoins int64
	LastAtMS       int64
}

func (r *Repository) getLuckyGiftRechargeSnapshot(ctx context.Context, tx *sql.Tx, userID int64, giftTypeCode string, nowMS int64) (luckyGiftRechargeSnapshot, error) {
	if userID <= 0 || !isLuckyGiftType(giftTypeCode) {
		return luckyGiftRechargeSnapshot{}, nil
	}
	now := time.UnixMilli(nowMS).UTC()
	dayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
	sevenDayStartMS := dayStart.AddDate(0, 0, -6).UnixMilli()
	thirtyDayStartMS := dayStart.AddDate(0, 0, -29).UnixMilli()
	// 业务时间范围统一使用 [start_ms,end_ms)。加 1ms 让发生在本事务时钟同一毫秒的已完成充值也属于“含当天”快照。
	endMS := nowMS + 1
	if endMS < nowMS { // int64 极值只可能来自坏时钟；退回不溢出的上界，避免范围反转。
		endMS = nowMS
	}
	var snapshot luckyGiftRechargeSnapshot
	err := tx.QueryRowContext(ctx, `
		SELECT
		  COALESCE(SUM(CASE WHEN created_at_ms >= ? THEN coin_amount ELSE 0 END), 0),
		  COALESCE(SUM(coin_amount), 0),
		  COALESCE(MAX(created_at_ms), 0)
		FROM wallet_recharge_records
		WHERE app_code = ? AND user_id = ?
		  AND created_at_ms >= ? AND created_at_ms < ?`,
		sevenDayStartMS,
		appcode.FromContext(ctx), userID,
		thirtyDayStartMS, endMS,
	).Scan(&snapshot.SevenDayCoins, &snapshot.ThirtyDayCoins, &snapshot.LastAtMS)
	return snapshot, err
}

func isLuckyGiftType(giftTypeCode string) bool {
	switch giftTypeCode {
	case "lucky", "super_lucky":
		return true
	default:
		return false
	}
}
