package com.gameplatform.server.task;

import com.gameplatform.server.mapper.history.DeviceStatusTransitionMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 设备状态变更记录清理任务
 * 定期清理24小时前的设备状态变更历史记录，避免表数据过大影响性能
 */
@Component
public class DeviceStatusTransitionCleanupTask {
    private static final Logger log = LoggerFactory.getLogger(DeviceStatusTransitionCleanupTask.class);

    private final DeviceStatusTransitionMapper deviceStatusTransitionMapper;

    public DeviceStatusTransitionCleanupTask(DeviceStatusTransitionMapper deviceStatusTransitionMapper) {
        this.deviceStatusTransitionMapper = deviceStatusTransitionMapper;
    }

    /**
     * 每6小时清理一次24小时前的记录
     * 执行时间：每天的 02:00, 08:00, 14:00, 20:00
     */
    @Scheduled(cron = "0 0 2,8,14,20 * * ?")
    public void cleanupOldRecords() {
        try {
            log.info("开始清理设备状态变更历史记录...");
            
            int deletedCount = deviceStatusTransitionMapper.deleteOldRecords();
            
            if (deletedCount > 0) {
                log.info("设备状态变更记录清理完成: 删除了{}条24小时前的记录", deletedCount);
            } else {
                log.debug("设备状态变更记录清理完成: 无需要清理的记录");
            }
            
        } catch (Exception e) {
            log.error("设备状态变更记录清理失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 手动触发清理任务（用于测试或紧急清理）
     * 可通过管理接口或其他方式调用
     */
    public int manualCleanup() {
        try {
            log.info("手动触发设备状态变更记录清理...");
            int deletedCount = deviceStatusTransitionMapper.deleteOldRecords();
            log.info("手动清理完成: 删除了{}条记录", deletedCount);
            return deletedCount;
        } catch (Exception e) {
            log.error("手动清理失败: {}", e.getMessage(), e);
            throw e;
        }
    }
}
