package com.aip.gateway.api.controller;

import com.aip.gateway.api.aip.model.AipLabel;
import com.aip.gateway.api.aip.model.AipTemplate;
import com.aip.gateway.api.model.response.ApiResponseModel;
import com.aip.gateway.api.repository.AppRepository;
import com.aip.gateway.api.repository.GlobalConstants;
import com.aip.gateway.api.service.IApiAipService;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Tag(name = "ApiAip", description = "AIP API")
@RestController
@RequiredArgsConstructor
@CrossOrigin
@Validated
@RequestMapping("/v1/aip-api/aip")
public class ApiAipController extends  BaseController {

    private final AppRepository appRepo;
    private final IApiAipService service;

    @Operation(summary = "AIP Download", description = "AIP Download API.")
    @ApiResponse(responseCode = "200", description = "AIP Download Success.")
    @ApiOperation(value = "AIP Download", response = ApiResponseModel.class)
    @PostMapping(value = "download", produces = {"application/json; charset=utf8"})
    public ResponseEntity<ApiResponseModel> downloadAipInfo(
            @Parameter(name = "apiKey", description = "API Key", example = "24826125-188B-4875-A841-F9146DD267F0", required = true)
            @RequestParam("apiKey") String apiKey,
            HttpServletRequest request)
    {
        GlobalConstants.setAuthorization(request, GlobalConstants.API_AIP_DOWNLOAD, apiKey, null);
        try {
            int authError = this.appRepo.checkApiKeyValidation(apiKey, getRemoteIP(request));
            if (authError != 0) {
                return responseApiKeyValidationError(request, authError);
            }
            return responseSuccess(this.service.downloadAipInfo());
        }
        catch (Exception e) {
            log.error("exception: /v1/aip-api/aip/download, {}", e.getMessage());
            return responseException(request, e);
        }
    }

    @Operation(summary = "AIP Label 조회", description = "AIP Label 조회.")
    @ApiResponse(responseCode = "200", description = "AIP Label query success.")
    @ApiOperation(value = "AIP Label 조회", response = ApiResponseModel.class, responseContainer = "ArrayList")
    @GetMapping(value = "labels", produces = {"application/json; charset=utf8"})
    public ResponseEntity<ApiResponseModel> getLabels(
            @Parameter(name = "apiKey", description = "API Key", example = "24826125-188B-4875-A841-F9146DD267F0", required = true) String apiKey,
            HttpServletRequest request)
    {
        try {
            GlobalConstants.setAuthorization(request, GlobalConstants.API_AIP_LABELS, apiKey, null);
            int authError = this.appRepo.checkApiKeyValidation(apiKey, getRemoteIP(request));
            if (authError != 0) {
                return responseApiKeyValidationError(request, authError);
            }
            List<AipLabel> response = this.service.getLabels();
            return ResponseEntity.ok().body(ApiResponseModel.builder()
                    .success(true)
                    .statusCode(HttpStatus.OK.value())
                    .message("success")
                    .result(response)
                    .build());
        }
        catch (Exception e) {
            log.error("exception: /v1/aip-api/aip/labels, {}", e.getMessage());
            return responseException(request, e);
        }
    }

    @Operation(summary = "AIP Policies 조회", description = "AIP Policies 조회.")
    @ApiResponse(responseCode = "200", description = "AIP Policies query success.")
    @ApiOperation(value = "AIP Policies 조회", response = ApiResponseModel.class, responseContainer = "ArrayList")
    @GetMapping(value = "policies", produces = {"application/json; charset=utf8"})
    public ResponseEntity<ApiResponseModel> getPolicies(
            @Parameter(name = "apiKey", description = "API Key", example = "24826125-188B-4875-A841-F9146DD267F0", required = true) String apiKey,
            HttpServletRequest request)
    {
        try {
            GlobalConstants.setAuthorization(request, GlobalConstants.API_AIP_POLICIES, apiKey, null);
            int authError = this.appRepo.checkApiKeyValidation(apiKey, getRemoteIP(request));
            if (authError != 0) {
                return responseApiKeyValidationError(request, authError);
            }
            List<AipLabel> response = this.service.getPolicies();
            return ResponseEntity.ok().body(ApiResponseModel.builder()
                    .success(true)
                    .statusCode(HttpStatus.OK.value())
                    .message("success")
                    .result(response)
                    .build());
        }
        catch (Exception e) {
            log.error("exception: /v1/aip-api/aip/policies, {}", e.getMessage());
            return responseException(request, e);
        }
    }

    @Operation(summary = "AIP Protections 조회", description = "AIP Protections 조회.")
    @ApiResponse(responseCode = "200", description = "AIP Protections query success.")
    @ApiOperation(value = "AIP Protections 조회", response = ApiResponseModel.class, responseContainer = "ArrayList")
    @GetMapping(value = "protections", produces = {"application/json; charset=utf8"})
    public ResponseEntity<ApiResponseModel> getLinkedApiKeys(
            @Parameter(name = "apiKey", description = "API Key", example = "24826125-188B-4875-A841-F9146DD267F0", required = true) String apiKey,
            HttpServletRequest request)
    {
        try {
            GlobalConstants.setAuthorization(request, GlobalConstants.API_AIP_PROTECTIONS, apiKey, null);
            int authError = this.appRepo.checkApiKeyValidation(apiKey, getRemoteIP(request));
            if (authError != 0) {
                return responseApiKeyValidationError(request, authError);
            }
            List<AipTemplate> response = this.service.getProtections();
            return ResponseEntity.ok().body(ApiResponseModel.builder()
                    .success(true)
                    .statusCode(HttpStatus.OK.value())
                    .message("success")
                    .result(response)
                    .build());
        }
        catch (Exception e) {
            log.error("exception: /v1/aip-api/aip/protections, {}", e.getMessage());
            return responseException(request, e);
        }
    }

}
