package douyin

import (
	"bindbox-game/internal/pkg/logger"
	"bindbox-game/internal/repository/mysql"
	"bindbox-game/internal/service/game"
	"bindbox-game/internal/service/sysconfig"
	"context"
	"strconv"
	"time"

	"go.uber.org/zap"
)

// StartDouyinOrderSync 启动抖店订单定时同步任务
func StartDouyinOrderSync(l logger.CustomLogger, repo mysql.Repo, syscfg sysconfig.Service, ticketSvc game.TicketService) {
	svc := New(l, repo, syscfg, ticketSvc)

	go func() {
		// 初始等待30秒让服务完全启动
		time.Sleep(30 * time.Second)

		for {
			ctx := context.Background()

			// 获取同步间隔配置
			intervalMinutes := 5 // 默认5分钟
			if c, err := syscfg.GetByKey(ctx, ConfigKeyDouyinInterval); err == nil && c != nil {
				if v, e := strconv.Atoi(c.ConfigValue); e == nil && v > 0 {
					intervalMinutes = v
				}
			}

			// 检查是否配置了 Cookie
			cookieCfg, err := syscfg.GetByKey(ctx, ConfigKeyDouyinCookie)
			if err != nil || cookieCfg == nil || cookieCfg.ConfigValue == "" {
				l.Debug("[抖店定时同步] Cookie 未配置，跳过本次同步")
				time.Sleep(time.Duration(intervalMinutes) * time.Minute)
				continue
			}

			// 执行同步
			l.Info("[抖店定时同步] 开始同步", zap.Int("interval_minutes", intervalMinutes))
			result, err := svc.FetchAndSyncOrders(ctx)
			if err != nil {
				l.Error("[抖店定时同步] 同步失败", zap.Error(err))
			} else {
				l.Info("[抖店定时同步] 同步成功",
					zap.Int("total_fetched", result.TotalFetched),
					zap.Int("new_orders", result.NewOrders),
					zap.Int("matched_users", result.MatchedUsers),
				)
			}

			// 等待下次同步
			time.Sleep(time.Duration(intervalMinutes) * time.Minute)
		}
	}()

	l.Info("[抖店定时同步] 定时任务已启动")
}
