package cokr.xit.ens.modules.ktsigntalk.gibis.presentation;

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.ctgy.mblpage.domain.SendDetailMblPage;
import cokr.xit.ens.modules.common.ctgy.mblpage.domain.ids.SendDetailMblPageIds;
import cokr.xit.ens.modules.common.ctgy.mblpage.domain.repository.SendDetailMblPageRepository;
import cokr.xit.ens.modules.common.ctgy.mblpage.presentation.MblPageControllerSupport;
import cokr.xit.ens.modules.ktsigntalk.gibis.domain.SendDetailKtGibis;
import cokr.xit.ens.modules.ktsigntalk.gibis.domain.repository.SendDetailKtGibisRepository;
import cokr.xit.ens.modules.ktsigntalk.gibis.service.KtGibisService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Tag(name = "KtGibisMblPageController")
@Slf4j
@RequiredArgsConstructor
@Controller
public class KtGibisMblPageController extends MblPageControllerSupport {

    private final KtGibisService ktGibisService;
    private final SendDetailKtGibisRepository sendDetailKtGibisRepository;
    private final SendDetailMblPageRepository sendDetailMblPageRepository;



//    @Parameters({
//            @Parameter(in = ParameterIn.QUERY, name = "token"),
//            @Parameter(in = ParameterIn.QUERY, name = "src_key"),
//            @Parameter(in = ParameterIn.QUERY, name = "external_document_uuid"),
//    })
    @GetMapping(value = "/kt/gibis/page/prnt")
    public String mblPagePrnt(@RequestParam Map<String, String> mParam, ModelMap model) {
        final String token = CmmnUtil.isEmpty(mParam.get("token")) ? null : mParam.get("token").replaceAll("[\\\"\\,\\[\\]]", "");
        final String srcKey = CmmnUtil.isEmpty(mParam.get("src_key")) ? null : mParam.get("src_key").replaceAll("[\\\"\\,\\[\\]]", "");
        final String serviceCd = CmmnUtil.isEmpty(mParam.get("service_cd")) ? null : mParam.get("service_cd").replaceAll("[\\\"\\,\\[\\]]", "");

        try {
            if (CmmnUtil.isEmpty(token) && CmmnUtil.isEmpty(srcKey))
                throw new EnsException(EnsErrCd.ERR410, "정상적인 요청이 아닙니다. 재인증 후 시도하시기 바랍니다.");
            SendDetailKtGibis sendDetail = sendDetailKtGibisRepository.findFetchByLinkedUuidAndSrcKey(null, srcKey)
                    .orElseThrow(() -> new EnsException(EnsErrCd.ERR404, "문서를 찾을 수 없습니다."));


            EnsResponseVO responseVO = ktGibisService.tokenVerify(sendDetail.getSendMast().getOrgCd(), srcKey, token, serviceCd);
            if (!EnsErrCd.OK.equals(responseVO.getErrCode()))
                throw new EnsException(responseVO.getErrCode(), responseVO.getErrMsg());


            SendDetailKtGibis sendDetailKtGibis = sendDetailKtGibisRepository.findBySrcKey(srcKey)
                    .orElseThrow(() -> new EnsException(EnsErrCd.ERR404, String.format("일치하는 자료가 없습니다. [ src_key %s ]", srcKey)));

            SendDetailMblPage sendDetailMblPage = sendDetailMblPageRepository.findById(SendDetailMblPageIds.builder()
                            .postSe(sendDetailKtGibis.getSendMast().getPostSe().getCode())
                            .sendDetailId(sendDetailKtGibis.getSendDetailId())
                            .build())
                    .orElseThrow(() -> new EnsException(EnsErrCd.ERR404, String.format("일치하는 페이지데이터가 없습니다. [ src_key %s ]", srcKey)));

            if (CmmnUtil.isEmpty(sendDetailMblPage.getDetails()))
                throw new EnsException(EnsErrCd.ERR401, String.format("details 필드 값이 비어있습니다. [ src_key %s ]", srcKey));

            model.put("details", sendDetailMblPage.getDetails());
            
            if ("Y".equals(sendDetailKtGibis.getMkBillUseYn())) {
                model.put("payBtnInf", getJsonPayBtnInf(sendDetailKtGibis.getBill(), sendDetailKtGibis.getSendMast()));
            }

            EnsResponseVO ensResponseVO = ktGibisService.readCmplt(sendDetail.getSendMast().getOrgCd(), token);
            if (!EnsErrCd.OK.equals(ensResponseVO.getErrCode()))
                throw new EnsException(ensResponseVO.getErrCode(), ensResponseVO.getErrMsg());
        } catch (EnsException e) {
            model.put("errCode", e.getErrCd());
            model.put("errMsg", e.getMessage());
            model.put("details", "{}");
        }

        return "modules/mblpage/notiprnt";
    }

}
