package com.caliverse.admin.scheduler;

import com.caliverse.admin.scheduler.entity.SchedulerType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SchedulerManager {
    // 재시도 설정
    private static final int MAX_RETRY_COUNT = 3;
    private static final long RETRY_DELAY_MS = 1000;

    // 실행 중인 작업 추적을 위한 Map
    private final Map<SchedulerType, Scheduler> schedulers  = new ConcurrentHashMap<>();

    public SchedulerManager(List<Scheduler> schedulerList) {
        schedulerList.forEach(scheduler ->
                schedulers.put(scheduler.getSchedulerType(), scheduler)
        );

        log.info("Initialized {} schedulers: {}",
                schedulerList.size(),
                schedulerList.stream()
                        .map(Scheduler::getSchedulerType)
                        .collect(Collectors.toList()));
    }

    public void executeScheduler(SchedulerType type) {
        Scheduler scheduler = schedulers.get(type);
        if (scheduler != null) {
            scheduler.execute();
        } else {
            log.warn("No scheduler found for type: {}", type);
        }
    }

    public void executeAllSchedulers() {
        schedulers.values().forEach(Scheduler::execute);
    }

    public void addScheduler(Scheduler scheduler) {
        schedulers.put(scheduler.getSchedulerType(), scheduler);
        log.info("Added scheduler: {}", scheduler.getSchedulerType());
    }

    public void removeScheduler(SchedulerType type) {
        schedulers.remove(type);
        log.info("Removed scheduler: {}", type);
    }
}
