package kr.xit.core.biz.batch.task;

import kr.xit.core.biz.batch.model.BatchCmmDTO.BatchLock;
import kr.xit.core.biz.batch.service.IBatchCmmService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;

/**
 * <pre>
 * description : 배치 종료시 lock table update
 *               종료하는 배치 인스턴스의 사용여부(use_yn)를 미사용(N)으로 변경
 *
 * packageName : kr.xit.core.biz.batch.task
 * fileName    : BatchEndTasklet
 * author      : limju
 * date        : 2023-05-16
 * ======================================================================
 * 변경일         변경자        변경 내용
 * ----------------------------------------------------------------------
 * 2023-05-16    limju       최초 생성
 *
 * </pre>
 * @see kr.xit.core.aop.TraceLoggerAspect
 */
@Slf4j
public class BatchFailEndTasklet implements Tasklet {
    private final IBatchCmmService batchCmmService;

    public BatchFailEndTasklet(IBatchCmmService batchCmmService) {
        this.batchCmmService = batchCmmService;
    }

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        String jobName = contribution.getStepExecution().getJobExecution().getJobInstance().getJobName();
        contribution.setExitStatus(ExitStatus.FAILED);
        BatchLock dto = BatchLock
                .builder()
                .instanceId(jobName)
                .result(contribution.getExitStatus().getExitCode())
                .message(MDC.get("service_error_msg"))
                .useYn("N")
                .batchLogId(MDC.get("batch_log_id"))
                .traceId(StringUtils.defaultString(MDC.get("request_trace_id"), MDC.get("request_trace_batch_id")))
                .build();

        batchCmmService.modifyBatchLock(dto);
        batchCmmService.modifyBatchLog(dto);
        return RepeatStatus.FINISHED;
    }
}
