package com.bsmlab.dfx.agent.config;

import com.bsmlab.dfx.agent.config.datasource.DynamicDataSourceService;
import com.bsmlab.dfx.agent.task.dropbox.DropBoxService;
import com.bsmlab.dfx.agent.task.dropbox.DropBoxSchedulerService;
import com.bsmlab.dfx.agent.task.postman.PostmanSchedulerService;
import com.bsmlab.dfx.agent.task.status.FileCleanerSchedulerService;
import com.bsmlab.dfx.agent.task.status.StatusCheckerSchedulerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Slf4j
@RequiredArgsConstructor
@Component
public class StartupRunner implements ApplicationRunner {
    private final DfxAgentConfiguration dfxAgentConfiguration;
    private final DynamicDataSourceService dynamicDataSourceService;
    private final PostmanSchedulerService postmanSchedulerService;
    private final DropBoxSchedulerService dropBoxSchedulerService;
    private final StatusCheckerSchedulerService statusCheckerSchedulerService;
    private final FileCleanerSchedulerService fileCleanerSchedulerService;
    private final DropBoxService dropBoxService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("✅ StartupRunner 기동");
        log.debug("System.getProperties(): \n{}", System.getProperties());
        // DfxAgentConfiguration 에서 생성한 빈 중 DataSource 관련 설정을 마무리한다.
        dynamicDataSourceService.setSqlSessionFactoryMap(dfxAgentConfiguration.getTemporarySqlSessionFactoryMap());
        dynamicDataSourceService.setTransactionManagerMap(dfxAgentConfiguration.getTemporaryTransactionManagerMap());
        //4. Worker 쓰레드 생성
        // 송신 메시지 전송 서비스
        log.info("✅ PostmanSchedulerService 기동");
        postmanSchedulerService.launch();
        // 수신한 메시지 처리 서비스
        log.info("✅ DropBoxTaskExecutorService 기동");
        dropBoxSchedulerService.launch();
        // 다른 agent 상태 확인 서비스
        log.info("✅ StatusCheckerSchedulerService 기동");
        statusCheckerSchedulerService.launch();
        // 처리 완료 파일 정리 서비스
        fileCleanerSchedulerService.launch();
        log.info("✅ FileCleanerSchedulerService 기동");
        // receivedMessageStorageRoot 하위에 처리되지 않은 메시지를 처리 queue에 넣는다.
        int messageCount = dropBoxService.addNotProcessedMessageFile();
        log.info("✅ 미처리 메시지 체크 - {} 건 처리 등록", messageCount);
        log.debug("✅ StartupRunner end");
    }
}
