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
}
