package user

import (
	"context"

	"bindbox-game/internal/repository/mysql/model"
)

func (s *service) ListCoupons(ctx context.Context, userID int64, page, pageSize int) (items []*model.UserCoupons, total int64, err error) {
	return s.ListCouponsByStatus(ctx, userID, 1, page, pageSize)
}

// ListCouponsByStatus 按状态获取用户优惠券列表
func (s *service) ListCouponsByStatus(ctx context.Context, userID int64, status int32, page, pageSize int) (items []*model.UserCoupons, total int64, err error) {
	q := s.readDB.UserCoupons.WithContext(ctx).ReadDB().Where(
		s.readDB.UserCoupons.UserID.Eq(userID),
		s.readDB.UserCoupons.Status.Eq(status),
	)
	total, err = q.Count()
	if err != nil {
		return nil, 0, err
	}
	if page <= 0 {
		page = 1
	}
	if pageSize <= 0 {
		pageSize = 20
	}
	if pageSize > 100 {
		pageSize = 100
	}
	items, err = q.Order(s.readDB.UserCoupons.ID.Desc()).Offset((page - 1) * pageSize).Limit(pageSize).Find()
	if err != nil {
		return nil, 0, err
	}
	return items, total, nil
}

// ListAppCoupons APP端查看优惠券（分类逻辑优化：未使用=未动过，已使用=部分使用or已用完）
// ListAppCoupons APP端查看优惠券（分类逻辑优化：未使用=未动过，已使用=部分使用or已用完）
func (s *service) ListAppCoupons(ctx context.Context, userID int64, tabType int32, page, pageSize int) (items []*model.UserCoupons, total int64, err error) {
	u := s.readDB.UserCoupons
	c := s.readDB.SystemCoupons

	// 使用 UnderlyingDB 绕过 GEN 的类型限制，确保 SQL 逻辑正确
	tableName := u.TableName()
	sysTableName := c.TableName()
	db := u.UnderlyingDB().WithContext(ctx).
		Table(tableName).
		Select("`"+tableName+"`.*").
		Joins("LEFT JOIN `"+sysTableName+"` ON `"+sysTableName+"`.id = `"+tableName+"`.coupon_id").
		Where("`"+tableName+"`.user_id = ?", userID)

	// 过滤逻辑
	switch tabType {
	case 0: // 未使用 (Status=1且余额>=满额)
		db = db.Where(u.TableName()+".status = ? AND "+u.TableName()+".balance_amount >= "+c.TableName()+".discount_value", 1)
	case 1: // 已使用 (Status=2 或 (Status=1且余额<满额))
		// Condition: (Status=1 AND Balance < Max) OR Status=2
		db = db.Where("("+u.TableName()+".status = ? AND "+u.TableName()+".balance_amount < "+c.TableName()+".discount_value) OR "+u.TableName()+".status = ?", 1, 2)
	case 2: // 已过期
		db = db.Where(u.TableName()+".status = ?", 3)
	default:
		// 默认只查未使用 (fallback to 0 logic)
		db = db.Where(u.TableName()+".status = ? AND "+u.TableName()+".balance_amount >= "+c.TableName()+".discount_value", 1)
	}

	// Count
	if err = db.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	if page <= 0 {
		page = 1
	}
	if pageSize <= 0 {
		pageSize = 20
	}

	// Find
	err = db.Order("`" + tableName + "`.id DESC").Offset((page - 1) * pageSize).Limit(pageSize).Scan(&items).Error
	if err != nil {
		return nil, 0, err
	}

	return items, total, nil
}
