package kr.xit.batch.ens.task;

import java.util.List;
import java.util.UUID;
import kr.xit.batch.ens.task.cmm.TaskCmmUtils;
import kr.xit.biz.ens.model.EnsDTO;
import kr.xit.biz.ens.model.cmm.SndngMssageParam;
import kr.xit.biz.ens.service.IEnsBatchSendService;
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    : SndngSendBulksTasklet
 * author      : limju
 * date        : 2023-06-12
 * ======================================================================
 * 변경일         변경자        변경 내용
 * ----------------------------------------------------------------------
 * 2023-06-12    limju       최초 생성
 *
 * </pre>
 */
@Slf4j
@RequiredArgsConstructor
public class SndngSendBulksTasklet implements Tasklet {
    private final IEnsBatchSendService service;
    @Override
    @JobScope
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
        final String isSlackEnabled = contribution.getStepExecution().getJobParameters().getString("isSlackEnabled");
        boolean isSuccess = true;

        try {
            MDC.put("request_trace_batch_id", UUID.randomUUID().toString().replace("-", ""));
            MDC.put("method", "POST");
            MDC.put("service_error_msg", "");

            List<SndngMssageParam> tgtList = service.findBulks(
                EnsDTO.BatchEnsRequest.builder()
                    .signguCode(
                        contribution.getStepExecution().getJobParameters().getString("signguCode"))
                    .ffnlgCode(
                        contribution.getStepExecution().getJobParameters().getString("ffnlgCode"))
                    .sndngProcessSttus(contribution.getStepExecution().getJobParameters()
                        .getString("sndngProcessSttus"))
                    .build()
            );

            for(SndngMssageParam dto : tgtList) {
                try {
                    dto.setSndngProcessSttus(contribution.getStepExecution().getJobParameters()
                        .getString("sndngProcessSttus"));
                    service.sendBulks(dto);

                } catch (Exception e) {
                    isSuccess = false;
                    String errMsg = ErrorParse.extractError(e).getMessage();
                    log.error("SndngSendBulksTasklet error :: {}", e.getMessage());
                    MDC.put("service_error_msg", errMsg);

                    TaskCmmUtils.taskBatchErrorLog(
                        contribution.getStepExecution().getJobExecution().getJobInstance()
                            .getJobName(),
                        errMsg,
                        isSlackEnabled
                    );

                    TaskCmmUtils.taskEnsBatchServiceUpdateErrorLog(
                        contribution.getStepExecution().getJobExecution().getJobInstance()
                            .getJobName(),
                        errMsg,
                        isSlackEnabled
                    );
                }
            }

        } finally {
            if(!isSuccess)  contribution.setExitStatus(ExitStatus.FAILED);
            else            contribution.setExitStatus(ExitStatus.COMPLETED);
            return RepeatStatus.FINISHED;
        }
    }
}
