package com.caliverse.admin.global.component.tracker;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class ExcelProgressTracker {
    private final Map<String, ProgressInfo> progressMap = new ConcurrentHashMap<>();

    @Data
    @AllArgsConstructor
    public static class ProgressInfo {
        private int currentStep;
        private int totalSteps;
        private String message;
        private long timestamp;

        public int getPercentage() {
            return totalSteps > 0 ? (currentStep * 100) / totalSteps : 0;
        }
    }

    public void updateProgress(String taskId, int currentStep, int totalSteps, String message) {
        progressMap.put(taskId, new ProgressInfo(currentStep, totalSteps, message, System.currentTimeMillis()));
        log.info("Progress [{}]: {}/{} - {}", taskId, currentStep, totalSteps, message);
    }

    public ProgressInfo getProgress(String taskId) {
        return progressMap.get(taskId);
    }

    public void removeProgress(String taskId) {
        progressMap.remove(taskId);
    }

    // 5분 이상 된 진행률 정보 자동 정리
    @Scheduled(fixedRate = 300000) // 5분마다
    public void cleanupOldProgress() {
        long fiveMinutesAgo = System.currentTimeMillis() - 300000;
        progressMap.entrySet().removeIf(entry -> entry.getValue().getTimestamp() < fiveMinutesAgo);
    }
}
