package user

import (
    "context"
    "strconv"
    "time"

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

func (s *service) AddPoints(ctx context.Context, userID int64, points int64, kind string, remark string, validStart *time.Time, validEnd *time.Time) error {
    if points == 0 {
        return nil
    }
    return s.writeDB.Transaction(func(tx *dao.Query) error {
        var existing *model.UserPoints
        if kind != "" {
            existing, _ = tx.UserPoints.WithContext(ctx).Where(tx.UserPoints.UserID.Eq(userID)).Where(tx.UserPoints.Kind.Eq(kind)).First()
        } else {
            existing, _ = tx.UserPoints.WithContext(ctx).Where(tx.UserPoints.UserID.Eq(userID)).First()
        }
        if existing == nil {
            item := &model.UserPoints{UserID: userID, Kind: kind, Points: points}
            if validStart != nil {
                item.ValidStart = *validStart
            }
            if validEnd != nil {
                item.ValidEnd = *validEnd
            }
            do := tx.UserPoints.WithContext(ctx)
            if validEnd == nil || validEnd.IsZero() {
                do = do.Omit(tx.UserPoints.ValidEnd)
            }
            if err := do.Create(item); err != nil {
                return err
            }
        } else {
            set := map[string]any{"points": existing.Points + points}
            if validStart != nil {
                set["valid_start"] = *validStart
            }
            if validEnd != nil {
                set["valid_end"] = *validEnd
            }
            if _, err := tx.UserPoints.WithContext(ctx).Where(tx.UserPoints.ID.Eq(existing.ID)).Updates(set); err != nil {
                return err
            }
        }
        ledger := &model.UserPointsLedger{UserID: userID, Action: "manual_add", Points: points, RefTable: "user_points", RefID: strconv.FormatInt(userID, 10), Remark: remark}
        if err := tx.UserPointsLedger.WithContext(ctx).Create(ledger); err != nil {
            return err
        }
        return nil
    })
}

