package worker

import (
	"context"
	"encoding/json"

	"kra/app/system/internal/biz"
	"kra/app/system/internal/conf"
	platformtask "kra/pkg/task"
)

// TaskMethods is the system module's dependency-bearing task contribution.
// Other modules provide their own contributor instead of editing this file.
type TaskMethods struct {
	tasks   *biz.TaskUsecase
	media   *biz.MediaUsecase
	runtime *conf.Runtime
}

func NewTaskMethods(tasks *biz.TaskUsecase, media *biz.MediaUsecase, runtime *conf.Runtime) *TaskMethods {
	return &TaskMethods{tasks: tasks, media: media, runtime: runtime}
}

var _ platformtask.Contributor = (*TaskMethods)(nil)

func (methods *TaskMethods) RegisterTasks(registry *platformtask.Registry) {
	if methods == nil || registry == nil {
		return
	}
	registry.Register(platformtask.Method{
		Name: biz.TaskMethodClearDB, Description: "清理数据库过期日志(操作记录/JWT黑名单/定时任务执行日志)", Run: func(ctx context.Context, _ json.RawMessage) error {
			return methods.tasks.CleanupLogs(ctx)
		},
	})
	registry.Register(platformtask.Method{
		Name: biz.TaskMethodUploads, Description: "清理过期大文件上传会话", Run: func(ctx context.Context, _ json.RawMessage) error {
			ttl := 24
			config := methods.runtime.Admin()
			if config != nil && config.Media != nil && config.Media.SessionTtl > 0 {
				ttl = int(config.Media.SessionTtl)
			}
			return methods.media.CleanupStale(ctx, ttl)
		},
	})
}
