package worker

import (
	"context"
	"encoding/json"
	"kra/internal/biz/system"
	taskbiz "kra/internal/biz/task"

	"kra/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       *taskbiz.TaskUsecase
	maintenance *system.MaintenanceUsecase
	media       *system.MediaUsecase
	runtime     *conf.Runtime
}

func NewTaskMethods(tasks *taskbiz.TaskUsecase, maintenance *system.MaintenanceUsecase, media *system.MediaUsecase, runtime *conf.Runtime) *TaskMethods {
	return &TaskMethods{tasks: tasks, maintenance: maintenance, 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: taskbiz.TaskMethodClearDB, Description: "清理数据库过期日志(操作记录/JWT黑名单/定时任务执行日志)", Run: func(ctx context.Context, _ json.RawMessage) error {
			if err := methods.maintenance.CleanupExpired(ctx); err != nil {
				return err
			}
			return methods.tasks.CleanupTaskLogs(ctx)
		},
	})
	registry.Register(platformtask.Method{
		Name: taskbiz.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)
		},
	})
}
