package task

import (
	"context"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
	"sundynix-micro-go/app/system/rpc/internal/svc"
)

// CleanOperLogJob 定义清理操作日志的定时任务
type CleanOperLogJob struct {
	svcCtx *svc.ServiceContext
}

func NewCleanOperLogJob(svcCtx *svc.ServiceContext) *CleanOperLogJob {
	return &CleanOperLogJob{
		svcCtx: svcCtx,
	}
}

func (j *CleanOperLogJob) Run() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
	defer cancel()

	logx.WithContext(ctx).Infof("[CRON] 开始执行定时清理操作日志任务")

	// 删除 3 天前的日志
	threeDaysAgo := time.Now().AddDate(0, 0, -3)

	// 执行硬删除
	res := j.svcCtx.DB.WithContext(ctx).Exec("DELETE FROM sundynix_operation_record WHERE created_at < ?", threeDaysAgo)
	if res.Error != nil {
		logx.WithContext(ctx).Errorf("[CRON] 清理操作日志失败: %v", res.Error)
		return
	}

	logx.WithContext(ctx).Infof("[CRON] 定时清理操作日志完成，共删除了 %d 条数据", res.RowsAffected)
}
