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

import cokr.xit.ens.core.utils.CmmnUtil;
import cokr.xit.ens.core.utils.IdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
@Profile({"local-test"})
public class BillKkoPayApiTest implements BillKkoPayApiSpec {

    @Value("${contract.kakao.pay.bill.dozn.host}")
    private String HOST;
    @Value("${contract.kakao.pay.bill.dozn.api.url}")
    private String API_URL;
    @Value("${contract.kakao.pay.bill.dozn.api.reurl}")
    private String API_RE_URL;

    /**
     * 청구서링크 생성
     *
     * @param billerCode
     * @param authorization
     * @param jsonStr
     * @return
     */
    @Override
    public ResponseEntity<String> url(String billerCode, String authorization, String jsonStr) {

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", authorization);
        headers.setContentType(new MediaType(MediaType.APPLICATION_JSON, Charset.forName("utf-8")));


        StringBuilder url = new StringBuilder();
        url.append(this.HOST)
                .append(this.API_URL.replace("{billerCode}", billerCode == null ? "" : billerCode));


        ResponseEntity<String> resp = this.callApi(HttpMethod.POST, url.toString(), jsonStr, headers);


        String uuid = IdGenerator.getUUID();
        String data = "{\"res_code\":\"OK\",\"message\":\"성공\",\"data\":{\"url\":\"https://billgatesweb.kakao.com/r/platform/pages/paynow/search/" + uuid + "\"}}";
        return ResponseEntity.ok(data);
    }


    /**
     * 청구서링크 재생성
     *
     * @param billerCode
     * @param authorization
     * @param jsonStr
     * @return
     */
    @Override
    public ResponseEntity<String> reUrl(String billerCode, String authorization, String jsonStr) {

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", authorization);
        headers.setContentType(new MediaType(MediaType.APPLICATION_JSON, Charset.forName("utf-8")));


        StringBuilder url = new StringBuilder();
        url.append(this.HOST)
                .append(this.API_RE_URL.replace("{billerCode}", billerCode == null ? "" : billerCode));


        ResponseEntity<String> resp = this.callApi(HttpMethod.POST, url.toString(), jsonStr, headers);


        String uuid = IdGenerator.getUUID();
        String data = "{\"res_code\":\"OK\",\"message\":\"성공\",\"data\":{\"url\":\"https://billgatesweb.kakao.com/r/platform/pages/paynow/search/" + uuid + "\"}}";
        return ResponseEntity.ok(data);
    }

    /**
     * <pre>메소드 설명: API 호출
     * </pre>
     *
     * @param method
     * @param url
     * @param body
     * @param headers
     * @return ResponseEntity 요청처리 후 응답객체
     * @author: 박민규
     * @date: 2021. 8. 4.
     * @apiNote: 사이트 참조 https://e2e2e2.tistory.com/15
     */
    private ResponseEntity<String> callApi(HttpMethod method, String url, String body, HttpHeaders headers) {

        StringBuffer sb = new StringBuffer();
        ResponseEntity<String> responseEntity = ResponseEntity.ok("test");
        try {

            HttpEntity<?> entity = null;
            UriComponents uri = null;
            switch (method) {
                case GET:
                    entity = new HttpEntity<>(headers);
                    uri = UriComponentsBuilder
                            .fromHttpUrl(String.format("%s?%s", url, body == null ? "" : body))
                            .build(false);
                    break;
                case POST:
                    entity = new HttpEntity<>(body, headers);
                    uri = UriComponentsBuilder
                            .fromHttpUrl(url)
                            .encode(StandardCharsets.UTF_8)
                            .build();
                    break;

                default:
                    break;
            }

            sb.append("\n  url => " + uri.toString())
                    .append("\n  method => " + method)
                    .append("\n  headers => " + entity.getHeaders().toString())
                    .append("\n  body => " + entity.getBody());
        } catch (Exception e) {
            log.error("call API 기타오류\n[ url ]: {} \n[ param ]: {} \n[ error ]: {}", url, body, CmmnUtil.printStackTraceToString(e));
        } finally {
            log.info("카카오페이 청구서 API\n[ REQUEST ]-----------------------------------------------------------------------\n{}\n[ RESPONSE ]-----------------------------------------------------------------------\n{}", sb.toString(), responseEntity.getBody());
        }


        return responseEntity;
    }

}
