package kr.xit.batch.ens.task;

import kr.xit.batch.ens.task.cmm.TaskCmmUtils;
import kr.xit.biz.ens.model.EnsDTO;
import kr.xit.biz.ens.service.IEnsBatchCloseService;
import kr.xit.core.exception.ErrorParse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.JobScope;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;

/**
 * <pre>
 * description :
 *
 * packageName : kr.xit.batch.ens.task
 * fileName    : SndngCloseTasklet
 * author      : seojh
 * date        : 2023-06-14
 * ======================================================================
 * 변경일         변경자        변경 내용
 * ----------------------------------------------------------------------
 * 2023-06-14    seojh       최초 생성
 *
 * </pre>
 */
@Slf4j
@RequiredArgsConstructor
public class SndngCloseTasklet implements Tasklet {
    private final IEnsBatchCloseService service;

    @Override
    @JobScope
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
        final String isSlackEnabled = contribution.getStepExecution().getJobParameters().getString("isSlackEnabled");

        try {
            MDC.put("service_error_msg", "");

            service.close(
                EnsDTO.BatchEnsRequest.builder()
                    .signguCode(contribution.getStepExecution().getJobParameters().getString("signguCode"))
                    .ffnlgCode(contribution.getStepExecution().getJobParameters().getString("ffnlgCode"))
                    .sndngProcessSttus(contribution.getStepExecution().getJobParameters().getString("sndngProcessSttus"))
                    .build()
            );
        }catch(Exception e){
            String errMsg = ErrorParse.extractError(e).getMessage();
            log.error("SndngCloseTasklet error :: {}", e.getMessage());
            MDC.put("service_error_msg", errMsg);
            TaskCmmUtils.taskBatchErrorLog(
                    contribution.getStepExecution().getJobExecution().getJobInstance().getJobName(),
                    errMsg,
                    isSlackEnabled
            );
            contribution.setExitStatus(ExitStatus.FAILED);
            return RepeatStatus.FINISHED;
        }
        contribution.setExitStatus(ExitStatus.COMPLETED);
        return RepeatStatus.FINISHED;
    }
}
