package com.eactive.eai.rms.onl.common.service;

import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.data.entity.onl.authserver.TokenIssuanceLogService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Slf4j
public class TokenIssuanceLogCleanupJob implements Job {
    
    private TokenIssuanceLogService tokenIssuanceLogService;
    
    @Autowired
    public TokenIssuanceLogCleanupJob(TokenIssuanceLogService tokenIssuanceLogService) {
    	this.tokenIssuanceLogService = tokenIssuanceLogService;    	
    }
        
    private static final int DEFAULT_DAYS_TO_KEEP = 7;
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("START TOKEN_ISSUANCE_LOG_CLEANUP_JOB...");
        try {
            List<DataSourceType> dataTypeList = DataSourceTypeManager.getOnlineDataSourceTypes();

            for (DataSourceType dataSourceType : dataTypeList) {
                DataSourceContextHolder.setDataSourceType(dataSourceType);
                long deletedCount = tokenIssuanceLogService.deleteOldLogs(DEFAULT_DAYS_TO_KEEP);
                log.info("Deleted {} old TokenIssuanceLog entries for data source: {}", deletedCount, dataSourceType.getJndiName());
            }
        } catch (Throwable th) {
            log.error("TokenIssuanceLog cleanup job failed", th);
            throw new JobExecutionException("FAILED TOKEN ISSUANCE LOG CLEANUP JOB", th);
        } finally {
            DataSourceContextHolder.clearDataSourceType();
        }
        log.info("FINISHED TOKEN_ISSUANCE_LOG_CLEANUP_JOB");
    }
}