package com.microservices.file.task;

import com.microservices.file.service.IChunkedUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 分片上传清理任务
 * <p>
 * 定时清理过期的上传会话和临时文件
 *
 * @author microservices
 */
@Component
public class ChunkedUploadCleanupTask {

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

    @Autowired
    private IChunkedUploadService chunkedUploadService;

    /**
     * 每小时执行一次清理过期会话
     * <p>
     * 清理规则：
     * 1. 会话状态为INIT/UPLOADING/FAILED且已过期（超过24小时）
     * 2. 清理对应的临时分片文件
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void cleanExpiredSessions() {
        logger.info("开始清理过期的分片上传会话");
        try {
            int cleanedCount = chunkedUploadService.cleanExpiredSessions();
            if (cleanedCount > 0) {
                logger.info("清理过期的分片上传会话完成，共清理{}个会话", cleanedCount);
            } else {
                logger.debug("没有需要清理的过期会话");
            }
        } catch (Exception e) {
            logger.error("清理过期的分片上传会话失败", e);
        }
    }
}
