package cokr.xit.ens.modules.kkoalimtalk.service.support;

import cokr.xit.ens.core.aop.EnsResponseVO;
import cokr.xit.ens.core.exception.EnsException;
import cokr.xit.ens.core.exception.code.EnsErrCd;
import cokr.xit.ens.core.utils.CmmnUtil;
import cokr.xit.ens.modules.common.domain.SendMast;
import cokr.xit.ens.modules.common.domain.repository.SendMastRepository;
import cokr.xit.ens.modules.common.biztmplt.EnsPhaseProcSupport;
import cokr.xit.ens.modules.kkoalimtalk.domain.SendDetailKkoAlimtalk;
import cokr.xit.ens.modules.kkoalimtalk.domain.repository.SendDetailKkoAlimtalkRepository;
import cokr.xit.ens.modules.kkoalimtalk.model.KkoAlimtalkRsltRespDTO;
import cokr.xit.ens.modules.kkoalimtalk.model.config.KkoAlimtalkStat;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class KkoAlimtalkRsltProvider implements EnsPhaseProcSupport<EnsResponseVO, Long> {

    private final SendMastRepository sendMastRepository;
    private final SendDetailKkoAlimtalkRepository sendDetailKkoAlimtalkRepository;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public EnsResponseVO statReady(List<Long> args) {
        log.info("no process");
        return null;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public EnsResponseVO statBegin(Long arg) {
        log.info("no process");
        return null;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public EnsResponseVO<KkoAlimtalkRsltRespDTO> execute(Long sendMastId) {
        try {
            SendMast sendMast = sendMastRepository.findById(sendMastId)
                    .orElseThrow(() -> new EnsException(EnsErrCd.PRVD404, String.format("일치하는 발송마스터 자료가 없습니다. [ sendMastId %s ]", sendMastId)));


            List<SendDetailKkoAlimtalk> sendDetailKkoAlimtalks = sendDetailKkoAlimtalkRepository.findAllFetchBySendMastId(sendMastId);
//            KkoAlimtalkRsltRespDTO respDTO = sendDetailKkoAlimtalkRepository.findKkoAlimtalkRsltRespDTOBysendMastId(sendMastId);
            KkoAlimtalkRsltRespDTO respDTO = KkoAlimtalkRsltRespDTO.builder()
                    .sendMastId(sendMast.getSendMastId())
                    .statCd(sendMast.getStatCd())
                    .orgCd(sendMast.getOrgCd())
                    .tmpltCd(sendMast.getTmpltCd())
                    .postBundleTitle(sendMast.getPostBundleTitle())
                    .sendDt(sendMast.getSendDt().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")))
                    .closeDt(sendMast.getCloseDt().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")))
                    .closeAt(true)
                    .documents(sendDetailKkoAlimtalks.stream()
                            .map(row -> KkoAlimtalkStat.builder()
                                    .sendDetailId(row.getSendDetailId())
                                    .msgIdx(row.getMsgIdx())
                                    .reqMsgIdx(row.getReqMsgIdx())
                                    .kkoResultCd(row.getKkoResultCd())
                                    .kkoRequestDt(row.getKkoRequestDt())
                                    .kkoReceivedDt(row.getKkoReceivedDt())
                                    .kkoSendType(row.getKkoSendType())
                                    .errorCode(CmmnUtil.isEmpty(row.getError())?null:row.getError().getErrorCode())
                                    .errorMessage(CmmnUtil.isEmpty(row.getError())?null:row.getError().getErrorMessage())
                                    .build())
                            .collect(Collectors.toList()))
                    .build();


            return EnsResponseVO.<KkoAlimtalkRsltRespDTO>okBuilder().resultInfo(respDTO).build();
        } catch (EnsException e) {
            return EnsResponseVO.<KkoAlimtalkRsltRespDTO>errRsltBuilder()
                    .errCode(e.getErrCd())
                    .errMsg(e.getMessage())
                    .resultInfo(KkoAlimtalkRsltRespDTO.builder()
                            .sendMastId(sendMastId)
                            .build())
                    .build();
        } catch (Exception e) {
            return EnsResponseVO.<KkoAlimtalkRsltRespDTO>errRsltBuilder()
                    .errCode(EnsErrCd.ERR999)
                    .errMsg(String.format("전송결과 응답 처리 실패. 실패사유: %s", e.getMessage()))
                    .resultInfo(KkoAlimtalkRsltRespDTO.builder()
                            .sendMastId(sendMastId)
                            .build())
                    .build();
        }

    }
}
