package com.common.schedule;

import com.common.service.ProbeHeartbeatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 探针心跳历史清理调度器
 * 定期清理过期的探针心跳历史记录
 */
@Component
public class ProbeHeartbeatHistoryCleanupScheduler {

    private static final Logger logger = LoggerFactory.getLogger(ProbeHeartbeatHistoryCleanupScheduler.class);

    @Autowired
    private ProbeHeartbeatService probeHeartbeatService;

    /** 保留天数，默认10天 */
    @Value("${probe.heartbeat.history.keep-days:10}")
    private int keepDays;

    /** 是否启用清理 */
    @Value("${probe.heartbeat.history.cleanup-enabled:true}")
    private boolean cleanupEnabled;

    /**
     * 每天凌晨1点执行清理
     */
    @Scheduled(cron = "${probe.history.cleanup.cron:0 0 1 * * ?}")
    public void cleanupHistory() {
        if (!cleanupEnabled) {
            logger.debug("心跳历史清理已禁用");
            return;
        }
        
        logger.info("========== 开始清理心跳历史记录 ==========");
        long startTime = System.currentTimeMillis();
        
        try {
            long deleted = probeHeartbeatService.cleanupHistory(keepDays);
            
            long elapsedTime = System.currentTimeMillis() - startTime;
            
            if (deleted > 0) {
                logger.info("心跳历史清理完成，删除 {} 条 {} 天前的记录, 耗时: {}ms", 
                        deleted, keepDays, elapsedTime);
            } else {
                logger.info("心跳历史清理完成，无过期记录需要清理, 耗时: {}ms", elapsedTime);
            }
        } catch (Exception e) {
            logger.error("心跳历史清理异常: {}", e.getMessage(), e);
        }
        
        logger.info("========== 心跳历史清理结束 ==========");
    }

    /**
     * 手动触发清理
     * @return 删除的记录数
     */
    public long manualCleanup() {
        logger.info("手动触发心跳历史清理");
        return probeHeartbeatService.cleanupHistory(keepDays);
    }
}
