package com.eactive.eai.rms.ext.djb.job;

import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.eactive.eai.rms.onl.apim.portalInquiry.PortalInquiryClosingService;
import com.eactive.eai.rms.onl.common.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 매일 00:05 실행 - RESPONDED 상태 문의글 자동 종료 배치
 *
 * <p>종료 조건 (기본 7일):</p>
 * <ul>
 *   <li>답변완료 후 댓글이 7일간 없는 경우</li>
 *   <li>관리자 댓글 등록 후 7일간 포탈사용자 댓글이 없는 경우</li>
 * </ul>
 *
 * <p>Cron: 0 5 0 * * ?</p>
 *
 * <p>Job 파라미터 (JobDataMap):</p>
 * <ul>
 *   <li>{@value #KEY_INQUIRY_COMMENT_CLOSING_DAY}: 종료 기준 일수 (기본값: 7)</li>
 * </ul>
 */
@DisallowConcurrentExecution
public class PortalInquiryClosingJob implements Job {

    private static final Logger log = LoggerFactory.getLogger(PortalInquiryClosingJob.class);

    /** Job 파라미터 키: 댓글종료 기간(일) */
    public static final String KEY_INQUIRY_COMMENT_CLOSING_DAY = "inquiry.comment.closing_day";

    private static final int DEFAULT_CLOSING_DAYS = 7;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();

        // execute.instances 가 지정된 경우 해당 인스턴스에서만 실행
        String allowedInstances = jobDataMap.getString("execute.instances");
        if (StringUtils.isNotEmpty(allowedInstances)) {
            Set<String> instanceSet = Arrays.stream(allowedInstances.split(","))
                    .map(s -> s.trim().toLowerCase())
                    .collect(Collectors.toSet());
            String currentInstance = StringUtils.defaultString(System.getProperty("inst.Name")).trim().toLowerCase();
            if (!instanceSet.contains(currentInstance)) {
                log.debug("Job 실행 인스턴스 제한 - 현재: {}, 허용: {}", currentInstance, allowedInstances);
                return;
            }
        }

        log.info("*** START PortalInquiryCommentClosingService run({})", CommonUtil.getToday("yyyy-MM-dd HH:mm"));

        PortalInquiryClosingService service;
        try {
            ApplicationContext appContext = (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
            service = appContext.getBean(PortalInquiryClosingService.class);
        } catch (SchedulerException e) {
            log.error("applicationContext 조회 실패", e);
            throw new JobExecutionException(e);
        }

        int closingDays = DEFAULT_CLOSING_DAYS;
        String closingDayParam = context.getMergedJobDataMap().getString(KEY_INQUIRY_COMMENT_CLOSING_DAY);
        if (closingDayParam != null) {
            try {
                closingDays = Integer.parseInt(closingDayParam);
            } catch (NumberFormatException e) {
                log.warn("잘못된 {} 파라미터 값: '{}', 기본값 {}일 사용", KEY_INQUIRY_COMMENT_CLOSING_DAY, closingDayParam, DEFAULT_CLOSING_DAYS);
            }
        }

        DataSourceContextHolder.setDataSourceType(
                DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.APIGW));
        try {
            int closedCount = service.closeExpiredInquiries(closingDays);
            log.info("PortalInquiryCommentClosingService 완료: {}건 CLOSED 처리", closedCount);
        } catch (Exception e) {
            log.error("PortalInquiryCommentClosingService execution failed", e);
            throw new JobExecutionException(e);
        } finally {
            DataSourceContextHolder.clearDataSourceType();
        }

        log.info("*** END PortalInquiryCommentClosingService run({})", DateUtil.getDateTime("yyyy-MM-dd HH:mm"));
    }
}
