package queue

import (
	"context"
	"fmt"
	"tydata-server/app/main/api/internal/svc"
	"tydata-server/app/main/api/internal/types"

	"github.com/hibiken/asynq"
)

type CronJob struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCronJob(ctx context.Context, svcCtx *svc.ServiceContext) *CronJob {
	return &CronJob{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CronJob) Register() *asynq.ServeMux {
	redisClientOpt := asynq.RedisClientOpt{Addr: l.svcCtx.Config.CacheRedis[0].Host, Password: l.svcCtx.Config.CacheRedis[0].Pass}
	scheduler := asynq.NewScheduler(redisClientOpt, nil)

	// 注册清理查询数据任务
	task := asynq.NewTask(types.MsgCleanQueryData, nil, nil)
	_, err := scheduler.Register(TASKTIME, task)
	if err != nil {
		panic(fmt.Sprintf("定时任务注册失败:%v", err))
	}
	scheduler.Start()
	fmt.Println("定时任务启动！！！")

	mux := asynq.NewServeMux()
	mux.Handle(types.MsgPaySuccessQuery, NewPaySuccessNotifyUserHandler(l.svcCtx))
	mux.Handle(types.MsgCleanQueryData, NewCleanQueryDataHandler(l.svcCtx))
	mux.Handle(types.MsgUnfreezeCommission, NewUnfreezeCommissionHandler(l.svcCtx))

	return mux
}
