package kr.xit.ens.ktgbs.service;

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

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import kr.xit.biz.cmm.service.ICmmEnsCacheService;
import kr.xit.biz.common.ApiConstants;
import kr.xit.biz.ens.model.cmm.CmmEnsRequestDTO;
import kr.xit.biz.ens.model.cmm.CmmEnsRlaybsnmDTO;
import kr.xit.biz.ens.model.kt.KtCommonDTO;
import kr.xit.biz.ens.model.ktgbs.KtGbsDTO;
import kr.xit.core.service.AbstractService;
import kr.xit.core.spring.annotation.TraceLogging;
import kr.xit.core.spring.util.ApiWebClientUtil;
import kr.xit.core.support.utils.DateUtils;
import kr.xit.core.support.utils.JsonUtils;
import kr.xit.ens.cmm.CmmEnsUtils;
import lombok.RequiredArgsConstructor;

/**
 * <pre>
 * description : 
 * packageName : kr.xit.ens.ktgbs.service
 * fileName    : KtGbsService
 * author      : limju
 * date        : 2024-08-19
 * ======================================================================
 * 변경일         변경자        변경 내용
 * ----------------------------------------------------------------------
 * 2024-08-19   limju       최초 생성
 *
 * </pre>
 */
@RequiredArgsConstructor
@Service
public class KtGbsService extends AbstractService implements IKtGbsService {
    @Value("${app.contract.ktgbs.host}")
    private String HOST;

    @Value("${app.contract.ktgbs.api.access-token}")
    private String API_ACCESS_TOKEN;

    /**
     * 토큰인증확인조회 : BC-AG-SN-008
     */
    @Value("${app.contract.ktgbs.api.cfm-token}")
    private String API_CFM_TOKEN;

    /**
     * 토큰열람확인결과전송 : BC-AG-SN-009
     */
    @Value("${app.contract.ktgbs.api.read-token}")
    private String API_READ_TOKEN;

    /**
     * 본문자수신등록
     */
    @Value("${app.contract.ktgbs.api.main-send}")
    private String API_MAIN_SEND;

    private final ApiWebClientUtil webClient;
    private final ICmmEnsCacheService cacheService;

    @Override
    @TraceLogging
    public KtGbsDTO.TokenResponse requestToken(final KtCommonDTO.KtMnsRequest paramDTO) {
        String profile = StringUtils.isEmpty(paramDTO.getProfile()) ? (ApiConstants.IS_PROFILE_LOCAL? "local" : "prod") : paramDTO.getProfile();
        paramDTO.setProfile(profile);
        final CmmEnsRlaybsnmDTO ktMnsInfo = cacheService.getRlaybsnmInfoCache(CmmEnsRequestDTO.builder()
            .signguCode(paramDTO.getSignguCode())
            .ffnlgCode(paramDTO.getFfnlgCode())
            .profile(paramDTO.getProfile())
            .build());

        final KtGbsDTO.TokenRequest reqDTO = KtGbsDTO.TokenRequest.builder()
            .clientId(ktMnsInfo.getKtSvcClientId())
            .clientSecret(ktMnsInfo.getKtSvcClientSecret())
            .build();
        CmmEnsUtils.validate(reqDTO);

        final Map<String,String> headerMap = new HashMap<>();
        headerMap.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        headerMap.put(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", ktMnsInfo.getKtAccessToken()));

        return webClient.exchangeFormData(
            HOST + API_ACCESS_TOKEN,
            HttpMethod.POST,
            reqDTO,
            KtGbsDTO.TokenResponse.class,
            headerMap
        );
    }

    @Override
    @TraceLogging
    public KtCommonDTO.KtCommonResponse cfmToken(final KtGbsDTO.TokenConfirmRequest reqDTO) {
        final CmmEnsRlaybsnmDTO ktMnsInfo = getRlaybsnmInfo(reqDTO);
        reqDTO.setServiceCd(ktMnsInfo.getKtServiceCode());
        reqDTO.setSignguCode(null);
        reqDTO.setFfnlgCode(null);
        reqDTO.setProfile(null);
        CmmEnsUtils.validate(reqDTO);

        return webClient.exchangeKtGbs(
            HOST + API_CFM_TOKEN,
            HttpMethod.POST,
            JsonUtils.toJson(reqDTO),
            KtCommonDTO.KtCommonResponse.class,
            ktMnsInfo
        );
    }

    @Override
    @TraceLogging
    public KtCommonDTO.KtCommonResponse readToken(final KtGbsDTO.TokenReadRequest reqDTO) {
        final CmmEnsRlaybsnmDTO ktMnsInfo = getRlaybsnmInfo(reqDTO);
        reqDTO.setServiceCd(ktMnsInfo.getKtServiceCode());
        reqDTO.setMmsRdgTmst(DateUtils.getTodayAndNowTime("yyyyMMddHHmmss"));
        reqDTO.setSignguCode(null);
        reqDTO.setFfnlgCode(null);
        reqDTO.setProfile(null);
        CmmEnsUtils.validate(reqDTO);

        return webClient.exchangeKtGbs(
            HOST + API_READ_TOKEN,
            HttpMethod.POST,
            JsonUtils.toJson(reqDTO),
            KtCommonDTO.KtCommonResponse.class,
            ktMnsInfo
        );
    }

    @Override
    @TraceLogging
    public KtCommonDTO.KtCommonResponse mainSend(final KtGbsDTO.MsgSendRequest reqDTO) {
        final CmmEnsRlaybsnmDTO ktMnsInfo = getRlaybsnmInfo(reqDTO);
        reqDTO.setServiceCd(ktMnsInfo.getKtServiceCode());
        reqDTO.setSignguCode(null);
        reqDTO.setFfnlgCode(null);
        reqDTO.setProfile(null);
        CmmEnsUtils.validate(reqDTO);

        return webClient.exchangeKtGbs(
            HOST + API_MAIN_SEND,
            HttpMethod.POST,
            JsonUtils.toJson(reqDTO),
            KtCommonDTO.KtCommonResponse.class,
            ktMnsInfo
        );
    }

    private CmmEnsRlaybsnmDTO getRlaybsnmInfo(final KtCommonDTO.KtMnsRequest request){
        return CmmEnsUtils.getRlaybsnmInfo(request.getSignguCode(), request.getFfnlgCode(), ApiConstants.SndngSeCode.KT_GIBIS);
    }
}
