package app

import (
	"bindbox-game/internal/pkg/core"
)

type couponStatsResponse struct {
	UnusedCount    int64 `json:"unused_count"`    // 可用优惠券数量
	UsedCount      int64 `json:"used_count"`      // 已使用优惠券数量
	ExpiredCount   int64 `json:"expired_count"`   // 已过期优惠券数量
	TotalRemaining int64 `json:"total_remaining"` // 可用优惠券总余额（分）
	TotalSaved     int64 `json:"total_saved"`     // 累计节省金额（分）
}

// GetUserCouponStats 获取用户优惠券统计
// @Summary 获取用户优惠券统计
// @Description 获取用户优惠券各状态数量和累计金额
// @Tags APP端.用户
// @Accept json
// @Produce json
// @Param user_id path integer true "用户ID"
// @Security LoginVerifyToken
// @Success 200 {object} couponStatsResponse
// @Failure 400 {object} code.Failure
// @Router /api/app/users/{user_id}/coupons/stats [get]
func (h *handler) GetUserCouponStats() core.HandlerFunc {
	return func(ctx core.Context) {
		rsp := new(couponStatsResponse)
		userID := int64(ctx.SessionUserInfo().Id)

		// 统计各状态数量
		unusedCount, _ := h.readDB.UserCoupons.WithContext(ctx.RequestContext()).ReadDB().
			Where(h.readDB.UserCoupons.UserID.Eq(userID), h.readDB.UserCoupons.Status.Eq(1)).Count()
		usedCount, _ := h.readDB.UserCoupons.WithContext(ctx.RequestContext()).ReadDB().
			Where(h.readDB.UserCoupons.UserID.Eq(userID), h.readDB.UserCoupons.Status.Eq(2)).Count()
		expiredCount, _ := h.readDB.UserCoupons.WithContext(ctx.RequestContext()).ReadDB().
			Where(h.readDB.UserCoupons.UserID.Eq(userID), h.readDB.UserCoupons.Status.Eq(3)).Count()

		// 统计可用优惠券总余额
		var totalRemaining int64
		_ = h.repo.GetDbR().Raw(
			"SELECT COALESCE(SUM(balance_amount), 0) FROM user_coupons WHERE user_id = ? AND status = 1",
			userID,
		).Scan(&totalRemaining).Error

		// 统计累计节省金额（所有使用记录的扣减金额总和）
		var totalSaved int64
		_ = h.repo.GetDbR().Raw(
			"SELECT COALESCE(SUM(ABS(change_amount)), 0) FROM user_coupon_ledger WHERE user_id = ? AND change_amount < 0",
			userID,
		).Scan(&totalSaved).Error

		rsp.UnusedCount = unusedCount
		rsp.UsedCount = usedCount
		rsp.ExpiredCount = expiredCount
		rsp.TotalRemaining = totalRemaining
		rsp.TotalSaved = totalSaved

		ctx.Payload(rsp)
	}
}
