package com.fizz.business.scheduled;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fizz.business.domain.LogData;
import com.fizz.business.service.LogDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 日志数据清理定时任务
 * 每天凌晨2点执行，删除六个月前的日志数据
 */
@Slf4j
@Component
public class LogDataCleanSchedule extends BaseSchedule {

    @Autowired
    private LogDataService logDataService;

    /**
     * 每天凌晨2点执行日志清理任务
     * cron表达式: 秒 分 时 日 月 周
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void cleanOldLogData() {
        String taskName = "日志数据清理任务";
        String cacheKey = "log_data_clean_task";
        
        execute(taskName, 3600, cacheKey, () -> {
            actionCatchException(() -> {
                // 计算六个月前的时间
                LocalDateTime sixMonthsAgo = LocalDateTime.now().minusMonths(6);
                
                log.info("开始清理六个月前的日志数据，截止时间: {}", sixMonthsAgo);
                
                // 删除六个月前的日志数据
                LambdaQueryWrapper<LogData> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.lt(LogData::getTimestamp, sixMonthsAgo);
                
                Long deletedCount = logDataService.count(queryWrapper);
                boolean result = logDataService.remove(queryWrapper);
                
                if (result) {
                    log.info("日志数据清理完成，共删除 {} 条记录", deletedCount);
                } else {
                    log.warn("日志数据清理失败");
                }
            });
        });
    }
}
