package user

import (
	"bindbox-game/internal/pkg/logger"
	"bindbox-game/internal/repository/mysql"
	"bindbox-game/internal/repository/mysql/dao"
	"context"
	"fmt"
	"time"
)

// StartExpirationCheck starts a background task to check and expire items and coupons
func StartExpirationCheck(l logger.CustomLogger, repo mysql.Repo) {
	go func() {
		// Check every minute
		t := time.NewTicker(1 * time.Minute)
		defer t.Stop()

		for range t.C {
			ctx := context.Background()
			db := dao.Use(repo.GetDbW())
			now := time.Now()

			// 1. Expire Item Cards
			// Status: 1 (Unused) -> 3 (Expired)
			result, err := db.UserItemCards.WithContext(ctx).
				Where(db.UserItemCards.Status.Eq(1), db.UserItemCards.ValidEnd.Lt(now)).
				Updates(map[string]interface{}{"status": 3})

			if err != nil {
				l.Error("Failed to expire item cards: " + err.Error())
			} else if result.RowsAffected > 0 {
				l.Info(fmt.Sprintf("[Scheduled] Expired %d item cards", result.RowsAffected))
			}

			resultC, errC := db.UserCoupons.WithContext(ctx).
				Where(db.UserCoupons.Status.In(1, 2, 4), db.UserCoupons.ValidEnd.Lt(now)).
				Updates(map[string]interface{}{"status": 3})

			if errC != nil {
				l.Error("Failed to expire coupons: " + errC.Error())
			} else if resultC.RowsAffected > 0 {
				l.Info(fmt.Sprintf("[Scheduled] Expired %d coupons", resultC.RowsAffected))
			}
		}
	}()
}
