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.modules.ktsigntalk.gibis.domain.SendDetailKtGibis;
import cokr.xit.ens.modules.ktsigntalk.gibis.domain.repository.SendDetailKtGibisRepository;
import cokr.xit.ens.modules.ktsigntalk.gibis.model.KtGibisAcceptReqDTO;
import cokr.xit.ens.modules.ktsigntalk.gibis.model.KtGibisRsltStatFwdDTO;
import cokr.xit.ens.modules.ktsigntalk.gibis.service.KtGibisService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "KtGibisController")
@Slf4j
@RequiredArgsConstructor
@RestController
public class KtGibisController {

    private final KtGibisService ktGibisService;
    private final SendDetailKtGibisRepository sendDetailKtGibisRepository;


    @Operation(summary = "접수")
    @PostMapping(value = "/kt/gibis/accept", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> accept(@RequestBody KtGibisAcceptReqDTO reqDTO) {

        EnsResponseVO responseVO = ktGibisService.accept(reqDTO);


        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }


    @io.swagger.v3.oas.annotations.parameters.RequestBody(required = true, content = {
            @Content(mediaType = "application/json", examples = {
                    @ExampleObject(name = "Sample Example..."
                            , summary = "제작"
                            , value = "{\"sendMastId\": 1}")
            })
    })
    @Operation(summary = "제작")
//    @PutMapping(value = "/kt/gibis/make", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/kt/gibis/make", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> make(@RequestBody Map<String, Long> mParam) {

        EnsResponseVO responseVO = ktGibisService.remake(mParam.get("sendMastId"));

        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }


    @Operation(summary = "제작(일괄)")
//    @PutMapping(value = "/kt/gibis/make/all", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/kt/gibis/make/all", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> makeAll() {

        EnsResponseVO responseVO = ktGibisService.makeAll();

        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }


    @io.swagger.v3.oas.annotations.parameters.RequestBody(required = true, content = {
            @Content(mediaType = "application/json", examples = {
                    @ExampleObject(name = "Sample Example..."
                            , summary = "(대량)전송요청"
                            , value = "{\"sendMastId\": 1}")
            })
    })
    @Operation(summary = "(대량)전송요청")
    @PostMapping(value = "/kt/gibis/send/bulk", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> sendBulk(@RequestBody Map<String, Long> mParam) {
        EnsResponseVO responseVO = ktGibisService.sendBulk(mParam.get("sendMastId"));

        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }

    @Operation(summary = "(대량)전송요청 일괄")
    @PostMapping(value = "/kt/gibis/send/bulk/all", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> sendBulkAll() {
        EnsResponseVO responseVO = ktGibisService.sendBulkAll();

        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }


   
//            @Content(mediaType = "application/json", examples = {
//                    @ExampleObject(name = "Sample Example..."
//                            , summary = "(대량)문서상태 갱신"
//                            , value = "{\"sendMastId\": 1}")
//            })
//    })
//    @Operation(summary = "(대량)문서상태 갱신")
//    @PutMapping(value = "/kt/gibis/stat/bulk", produces = MediaType.APPLICATION_JSON_VALUE)
    @Operation(summary = "(대량)문서상태 갱신")
    @PostMapping(value = "/kt/gibis/stat/bulk", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map<String, Object>> statBulk(@RequestBody KtGibisRsltStatFwdDTO reqDto) {

        Map<String, Object> resultInfo = new HashMap<>();
        List<Map<String, String>> errors = new ArrayList<>();
        try {
            EnsResponseVO responseVO = ktGibisService.statBulk(reqDto);

            if (!EnsErrCd.OK.equals(responseVO.getErrCode()))
                throw new EnsException(responseVO.getErrCode(), responseVO.getErrMsg());

            resultInfo.put("result_cd", "00"); 
            resultInfo.put("result_dt", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        } catch (EnsException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error_msg", String.format("[%s] %s", e.getErrCd(), e.getMessage()));
            errors.add(error);
            resultInfo.put("result_cd", "01"); 
            resultInfo.put("result_dt", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
            resultInfo.put("errors", errors);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error_msg", String.format("[%s] %s", EnsErrCd.ERR999, e.getMessage()));
            errors.add(error);
            resultInfo.put("result_cd", "01"); 
            resultInfo.put("result_dt", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
            resultInfo.put("errors", errors);
        }

        return new ResponseEntity<Map<String, Object>>(resultInfo, HttpStatus.OK);
    }

//    @Operation(summary = "(대량)문서상태 일괄 갱신")
////    @PutMapping(value = "/kt/gibis/stat/bulk/all", produces = MediaType.APPLICATION_JSON_VALUE)
//    @PostMapping(value = "/kt/gibis/stat/bulk/all", produces = MediaType.APPLICATION_JSON_VALUE)
//    public ResponseEntity<EnsResponseVO> statBulkAll() {
//
//        EnsResponseVO responseVO = ktGibisService.statBulkAll();
//
//        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
//    }


    @io.swagger.v3.oas.annotations.parameters.RequestBody(required = true, content = {
            @Content(mediaType = "application/json", examples = {
                    @ExampleObject(name = "Sample Example..."
                            , summary = "토큰(OTT) 검증"
                            , value = "{\"src_key\": \"05vmGcudGY-dda1c242-5893-4451-835f-34cf3b00f812\", \"token\": \"ZDU3NGU1ZTYtNTk2Yy99OGNjLWJiYjUtYjZmMjI9NzRhOTA4\", \"service_cd\": \"CDO001\"}")
            })
    })
    @Operation(summary = "토큰(OTT) 검증")
    @PostMapping(value = "/kt/gibis/token/verify", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> tokenVerify(@RequestBody Map<String, String> mParam) {

        final String srcKey = mParam.get("src_key");
        final String token = mParam.get("token");
        final String serviceCd = mParam.get("service_cd");


        SendDetailKtGibis sendDetail = sendDetailKtGibisRepository.findFetchByLinkedUuidAndSrcKey(null, srcKey)
                .orElseThrow(() -> new EnsException(EnsErrCd.ERR404, "문서를 찾을 수 없습니다."));

        EnsResponseVO responseVO = ktGibisService.tokenVerify(sendDetail.getSendMast().getOrgCd(), srcKey, token, serviceCd);

        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }


    @io.swagger.v3.oas.annotations.parameters.RequestBody(required = true, content = {
            @Content(mediaType = "application/json", examples = {
                    @ExampleObject(name = "Sample Example..."
                            , summary = "전송결과 가져오기"
                            , value = "{\"sendMastId\": 1}")
            })
    })
    @Operation(summary = "전송결과 가져오기")
    @PostMapping(value = "/kt/gibis/send/result/provide", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> sendResultProvide(@RequestBody Map<String, Long> mParam) {

        EnsResponseVO responseVO = ktGibisService.sendResultProvide(mParam.get("sendMastId"));


        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }

    @Operation(summary = "인증토큰 갱신")
    @GetMapping(value = "/kt/gibis/refresh/auth/token/{orgCd}/{clientId}/{clientSecret}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> refreshAuthToken(@PathVariable String orgCd, @PathVariable String clientId, @PathVariable String clientSecret) {

        EnsResponseVO responseVO = ktGibisService.refreshAuthToken(orgCd, clientId, clientSecret);

        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }

    @Operation(summary = "인증토큰 갱신")
    @GetMapping(value = "/kt/gibis/read/cmplt", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> readCmplt(@RequestBody Map<String, String> mParam) {

        final String orgCd = mParam.get("orgCd");
        final String token = mParam.get("token");

        EnsResponseVO responseVO = ktGibisService.readCmplt(orgCd, token);


        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }


}
