package cokr.xit.ens.modules.common.ctgy.intgrnbill.nv.service;

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.intgrnbill.nv.entity.BillNvEasyPay;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.nv.entity.QBillNvEasyPay;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.nv.entity.repository.BillNvEasyPayRepository;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.support.code.PayUseSysResCd;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.support.entity.Bill;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.support.model.PayApiRespDTO;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.support.service.trigger.PaymentTriggerServiceTemplate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Slf4j
@RequiredArgsConstructor
@Service(value = "nvPaymentTriggerService")
public class NvPaymentTriggerService extends PaymentTriggerServiceTemplate {
    private final NvPayProcessService nvPayProcessService;
    private final JPAQueryFactory query;
    private final BillNvEasyPayRepository billNvEasyPayRepository;
    @Value("${contract.naver.pay.easy.ep-sdk-mode}")
    private String EP_SDK_MODE;

    @Override
    protected boolean existsBill(String billUid) {
        return query.selectFrom(QBillNvEasyPay.billNvEasyPay)
                .where(QBillNvEasyPay.billNvEasyPay.billUid.eq(billUid))
                .fetchCount() > 0;
    }

    @Override
    protected void generateBill(Bill bill) {
        billNvEasyPayRepository.save(BillNvEasyPay.builder()
                .billUid(bill.getBillUid())
                .billerUserKey(bill.getBillerUserKey())
                .payType("normal")
                .openType("page")
                .build());
    }

    @Override
    protected Map<String, Object> getPayInfo(Map<PTriggerDataKeys, Object> param) {
        final Bill bill = (Bill) param.getOrDefault(PTriggerDataKeys.bill, new Bill());
        final String billUid = (String) param.getOrDefault(PTriggerDataKeys.billUid, "");

        
        if (CmmnUtil.isEmpty(bill.getOrgMng().getNvBpClientId()))
            throw new EnsException(EnsErrCd.INVALID_DATA, "네이버 간편결제 계약정보가 없습니다.");

        
        Map<String, Object> p = new HashMap<>();
        p.put("billUid", billUid);
        PayApiRespDTO payApiRespDTO = nvPayProcessService.payNotice(p);
        if (!PayUseSysResCd.OK.getCode().equals(payApiRespDTO.getResCode()))
            throw new EnsException(EnsErrCd.RESPONSED_FAILURE_CODE, String.format("%s\n[실패사유]\n -.코드: %s\n -.메시지: %s", EnsErrCd.RESPONSED_FAILURE_CODE.getCodeNm(), payApiRespDTO.getResCode(), payApiRespDTO.getMessage()));
        
        BillNvEasyPay billNvEasyPay = Optional.ofNullable(query.selectFrom(QBillNvEasyPay.billNvEasyPay)
                        .where(QBillNvEasyPay.billNvEasyPay.billUid.eq(billUid))
                        .fetchOne())
                .orElseThrow(() -> new EnsException(EnsErrCd.NO_DATA_FOUND, "일치하는 청구서 자료가 없습니다."));


        
        Map<String, Object> resultInfo = new HashMap<>();
        resultInfo.put("mode", EP_SDK_MODE);
        resultInfo.put("payType", billNvEasyPay.getPayType());
        resultInfo.put("openType", billNvEasyPay.getOpenType());
        resultInfo.put("clientId", bill.getOrgMng().getNvBpClientId());
        resultInfo.put("billUid", billUid);
        resultInfo.put("merchantUserKey", billNvEasyPay.getBillerUserKey());
        resultInfo.put("merchantPayKey", billNvEasyPay.getBillUid());
        resultInfo.put("payinf", payApiRespDTO.getData());

        return resultInfo;
    }


}
