package com.dbnt.kcscbackend.admin.standards;

import com.dbnt.kcscbackend.admin.standards.entity.TnApiKey;
import com.dbnt.kcscbackend.admin.standards.service.AdminApiService;
import com.dbnt.kcscbackend.auth.entity.LoginVO;
import com.dbnt.kcscbackend.config.common.BaseController;
import com.dbnt.kcscbackend.config.common.ResponseCode;
import com.dbnt.kcscbackend.config.common.ResultVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/standards")
@Tag(name="AdminStandardsController", description = "사이트관리 건설기준관리 메뉴 컨트롤러")
public class AdminStandardsController extends BaseController {

    private final AdminApiService adminApiService;

    @Operation(
            summary = "건설기준관리 - API 관리",
            description = "API 관리",
            tags = {"AdminStandardsController"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "조회 성공"),
            @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
    })
    @RequestMapping(method = RequestMethod.POST, value = "/apikey", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResultVO selectApiList(@RequestBody TnApiKey tnApiKey, @AuthenticationPrincipal LoginVO user)
            throws Exception {

        ResultVO resultVO = new ResultVO();
        tnApiKey.setQueryInfo();
        Map<String, Object> resultMap = adminApiService.selectApiList();
        int totCnt = Integer.parseInt((String)resultMap.get("resultCnt"));
        tnApiKey.setContentCnt(totCnt);
        tnApiKey.setPaginationInfo();
        resultMap.put("paginationInfo", tnApiKey);

        resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
        resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
        resultVO.setResult(resultMap);
        return resultVO;
    }

    @Operation(
            summary = "API key 관리",
            description = "API key 승인여부 수정",
            tags = {"AdminStandardsController"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "수정 성공"),
            @ApiResponse(responseCode = "303", description = "만료된 토큰"),
            @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
    })
    @RequestMapping(method = RequestMethod.POST, value = "/apiupdate", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResultVO modifyApi(@RequestBody TnApiKey tnApiKey, @AuthenticationPrincipal LoginVO user) throws Exception{
        ResultVO resultVO = new ResultVO();

        TnApiKey existingApiKey = adminApiService.getApiKeyById(tnApiKey.getUserId());
        if (existingApiKey != null) {
            existingApiKey.setIdntyYn(existingApiKey.getIdntyYn().equals("Y") ? "N" : "Y");
            adminApiService.modifyApi(existingApiKey);

            resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
        } else {
            resultVO.setResultCode(ResponseCode.SAVE_ERROR.getCode());      // 존재하지 않는 user_id에 대한 처리
        }
        return resultVO;
    }

    @Operation(
            summary = "API key Chart",
            description = "API key 클릭시 차트",
            tags = {"AdminStandardsController"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "수정 성공"),
            @ApiResponse(responseCode = "303", description = "만료된 토큰"),
            @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
    })
    @RequestMapping(method = RequestMethod.POST, value = "/apiDailyChart", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResultVO ApiChart(@RequestBody Map<String, String> dateRange, @AuthenticationPrincipal LoginVO user) throws Exception{
        ResultVO resultVO = new ResultVO();
        Map<String, Object> resultMap = new HashMap<>();

        String UserId = dateRange.get("userId");

        resultMap.put("resultList", adminApiService.selectApiDailyCount(UserId));
        resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
        resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
        resultVO.setResult(resultMap);
        return resultVO;
    }
}
