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

import cokr.xit.ens.core.exception.EnsException;
import cokr.xit.ens.core.exception.code.EnsErrCd;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.kko.entity.BillKkoPay;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.kko.entity.QBillKkoPay;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.kko.entity.repository.BillKkoPayRepository;
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.stereotype.Service;

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


@Slf4j
@RequiredArgsConstructor
@Service(value = "kkoPaymentTriggerService")
public class KkoPaymentTriggerService extends PaymentTriggerServiceTemplate {
    private final KkoPayProcessService kkoPayProcessService;
    private final JPAQueryFactory query;
    private final BillKkoPayRepository billKkoPayRepository;

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

    @Override
    protected void generateBill(Bill bill) {
        billKkoPayRepository.save(BillKkoPay.builder()
                .billUid(bill.getBillUid())
                .billerUserKey(bill.getBillerUserKey())
                .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, "");

        
        Map<String, Object> p = new HashMap<>();
        p.put("billUid", billUid);
        PayApiRespDTO payApiRespDTO = kkoPayProcessService.gnrUrl(p);
        if (PayUseSysResCd.OK.getCode().equals(payApiRespDTO.getResCode())) {
            Map<String, Object> data = (Map<String, Object>) payApiRespDTO.getData();
            Map<String, Object> resultInfo = new HashMap<>();
            resultInfo.put("url", data.get("url"));

            return resultInfo;
        } else {
            throw new EnsException(EnsErrCd.RESPONSED_FAILURE_CODE, String.format("%s\n[실패사유]\n -.코드: %s\n -.메시지: %s", EnsErrCd.RESPONSED_FAILURE_CODE.getCodeNm(), payApiRespDTO.getResCode(), payApiRespDTO.getMessage()));
        }


    }

}
