package user

import (
    "context"
    "time"

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

func (s *service) AddCoupon(ctx context.Context, userID int64, couponID int64) error {
    tpl, err := s.readDB.SystemCoupons.WithContext(ctx).Where(s.readDB.SystemCoupons.ID.Eq(couponID)).First()
    if err != nil {
        return err
    }
    if tpl == nil || tpl.Status != 1 {
        return nil
    }
    item := &model.UserCoupons{UserID: userID, CouponID: couponID, Status: 1}
    if !tpl.ValidStart.IsZero() {
        item.ValidStart = tpl.ValidStart
    } else {
        item.ValidStart = time.Now()
    }
    if !tpl.ValidEnd.IsZero() {
        item.ValidEnd = tpl.ValidEnd
    }
    do := s.writeDB.UserCoupons.WithContext(ctx).Omit(s.readDB.UserCoupons.UsedAt, s.readDB.UserCoupons.UsedOrderID)
    if tpl.ValidEnd.IsZero() {
        do = do.Omit(s.writeDB.UserCoupons.ValidEnd)
    }
    return do.Create(item)
}

