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

import java.time.format.*;
import java.util.*;
import java.util.stream.*;

import org.springframework.stereotype.*;
import org.springframework.transaction.annotation.*;

import cokr.xit.ens.core.aop.*;
import cokr.xit.ens.core.exception.*;
import cokr.xit.ens.core.exception.code.*;
import cokr.xit.ens.core.utils.*;
import cokr.xit.ens.modules.common.biztmplt.*;
import cokr.xit.ens.modules.common.code.*;
import cokr.xit.ens.modules.common.domain.*;
import cokr.xit.ens.modules.common.domain.repository.*;
import cokr.xit.ens.modules.kkotalk.mapper.*;
import cokr.xit.ens.modules.kkotalk.model.*;
import cokr.xit.ens.modules.kkotalk.model.config.*;
import lombok.*;
import lombok.extern.slf4j.*;

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

    private final SendMastRepository sendMastRepository;
    private final IKkoTalkMapper talkMapper;

    @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<?> execute(Long sendMastId) {
        try {
            SendMast sendMast = sendMastRepository.findById(sendMastId)
                    .orElseThrow(() -> new EnsException(EnsErrCd.PRVD404, String.format("일치하는 발송마스터 자료가 없습니다. [ sendMastId %s ]", sendMastId)));
            List<SendDetailKkoTalkDTO> sendDetailKkoTalks = talkMapper.findAllBySendMastId(sendMast.getSendMastId());


            KkoTalkRsltRespDTO respDTO = KkoTalkRsltRespDTO.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(this.getCloseAt(sendMast))
                    .documents(sendDetailKkoTalks.stream()
                            .map(row -> KkoTalkStat.builder()
                                    .sendDetailId(row.getSendDetailId())
                                    .externalId(row.getExternalId())
                                    .envelopeId(row.getEnvelopeId())
                                    .status(row.getStatus())
                                    .sentDt(row.getSentAt())
                                    .receivedDt(row.getReceivedAt())
                                    .authenticatedAt(row.getAuthenticatedAt())
                                    .ottVerifiedAt(row.getOttVerifiedAt())
                                    .readAt(row.getReadAt())
                                    .userNotifiedAt(row.getUserNotifiedAt())
                                    .errorCode(CmmnUtil.isEmpty(row.getErrorCode()) ? null : row.getErrorCode())
                                    .errorMessage(CmmnUtil.isEmpty(row.getErrorMessage()) ? null : row.getErrorMessage())
                                    .build())
                            .collect(Collectors.toList()))
                    .build();

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

    }

    private boolean getCloseAt(SendMast sendMast) {
        if (StatCd.close.equals(sendMast.getStatCd()))
            return true;

        return StatCd.sendfail.equals(sendMast.getStatCd());
    }
}
