package com.kamco.cd.kamcoback.code;

import com.kamco.cd.kamcoback.code.config.CommonCodeCacheManager;
import com.kamco.cd.kamcoback.code.dto.CommonCodeDto;
import com.kamco.cd.kamcoback.code.service.CommonCodeService;
import com.kamco.cd.kamcoback.common.enums.DetectionClassification;
import com.kamco.cd.kamcoback.config.api.ApiResponseDto;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.Clazzes;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
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 jakarta.validation.Valid;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "공통코드 관리", description = "공통코드 관리 API")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/code")
public class CommonCodeApiController {

  private final CommonCodeService commonCodeService;
  private final CommonCodeCacheManager commonCodeCacheManager;

  @Operation(summary = "목록 조회", description = "모든 공통코드 조회")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "조회 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = CommonCodeDto.Basic.class))),
        @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @GetMapping
  public ApiResponseDto<List<CommonCodeDto.Basic>> getFindAll() {
    return ApiResponseDto.createOK(commonCodeService.getFindAll());
  }

  @Operation(summary = "단건 조회", description = "단건 조회")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "조회 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = CommonCodeDto.Basic.class))),
        @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @GetMapping("/{id}")
  public ApiResponseDto<CommonCodeDto.Basic> getOneById(
      @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "단건 조회", required = true)
          @PathVariable
          Long id) {
    return ApiResponseDto.ok(commonCodeService.getOneById(id));
  }

  @Operation(summary = "저장", description = "공통코드를 저장 합니다.")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "201",
            description = "공통코드 저장 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = Long.class))),
        @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
        @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @PostMapping
  public ApiResponseDto<ApiResponseDto.ResponseObj> save(
      @io.swagger.v3.oas.annotations.parameters.RequestBody(
              description = "공통코드 생성 요청 정보",
              required = true,
              content =
                  @Content(
                      mediaType = "application/json",
                      schema = @Schema(implementation = CommonCodeDto.AddReq.class)))
          @RequestBody
          @Valid
          CommonCodeDto.AddReq req) {
    return ApiResponseDto.okObject(commonCodeService.save(req));
  }

  @Operation(summary = "수정", description = "공통코드를 수정 합니다.")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "204",
            description = "공통코드 수정 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = Long.class))),
        @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
        @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @PutMapping("/{id}")
  public ApiResponseDto<ApiResponseDto.ResponseObj> update(
      @io.swagger.v3.oas.annotations.parameters.RequestBody(
              description = "공통코드 수정 요청 정보",
              required = true,
              content =
                  @Content(
                      mediaType = "application/json",
                      schema = @Schema(implementation = CommonCodeDto.ModifyReq.class)))
          @PathVariable
          Long id,
      @RequestBody @Valid CommonCodeDto.ModifyReq req) {
    return ApiResponseDto.okObject(commonCodeService.update(id, req));
  }

  @Operation(summary = "삭제", description = "공통코드를 삭제 합니다.")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "204",
            description = "공통코드 삭제 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = Long.class))),
        @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
        @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @DeleteMapping("/{id}")
  public ApiResponseDto<ApiResponseDto.ResponseObj> remove(
      @io.swagger.v3.oas.annotations.parameters.RequestBody(
              description = "공통코드 삭제 요청 정보",
              required = true)
          @PathVariable
          Long id) {
    return ApiResponseDto.okObject(commonCodeService.removeCode(id));
  }

  @Operation(summary = "순서 변경", description = "공통코드 순서를 변경 합니다.")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "204",
            description = "공통코드 순서 변경 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = Long.class))),
        @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
        @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @PutMapping("/order")
  public ApiResponseDto<ApiResponseDto.ResponseObj> updateOrder(
      @io.swagger.v3.oas.annotations.parameters.RequestBody(
              description = "공통코드 순서변경 요청 정보",
              required = true,
              content =
                  @Content(
                      mediaType = "application/json",
                      schema = @Schema(implementation = CommonCodeDto.OrderReq.class)))
          @RequestBody
          @Valid
          CommonCodeDto.OrderReq req) {

    return ApiResponseDto.okObject(commonCodeService.updateOrder(req));
  }

  @Operation(summary = "code 기반 조회", description = "code 기반 조회")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "code 기반 조회 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = Long.class))),
        @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
        @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @GetMapping("/used")
  public ApiResponseDto<List<CommonCodeDto.Basic>> getByCode(
      @io.swagger.v3.oas.annotations.parameters.RequestBody(
              description = "공통코드 순서변경 요청 정보",
              required = true)
          @RequestParam
          String code) {
    return ApiResponseDto.ok(commonCodeService.findByCode(code));
  }

  @GetMapping("/clazz")
  public ApiResponseDto<List<InferenceResultDto.Clazzes>> getClasses() {

    List<Clazzes> list =
        Arrays.stream(DetectionClassification.values())
            .sorted(Comparator.comparingInt(DetectionClassification::getOrder))
            .map(Clazzes::new)
            .toList();

    return ApiResponseDto.ok(list);
  }

  @Operation(summary = "공통코드 중복여부 체크", description = "공통코드 중복여부 체크")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "조회 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = CommonCodeDto.Basic.class))),
        @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @GetMapping("/check-duplicate")
  public ApiResponseDto<ApiResponseDto.ResponseObj> getCodeCheckDuplicate(
      @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "단건 조회", required = true)
          @RequestParam
          Long parentId,
      @RequestParam String code) {
    return ApiResponseDto.okObject(commonCodeService.getCodeCheckDuplicate(parentId, code));
  }

  @Operation(summary = "캐시 갱신", description = "공통코드 캐시를 갱신합니다. 공통코드 설정 변경 후 호출해주세요.")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "캐시 갱신 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = String.class))),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @PostMapping("/cache/refresh")
  public ApiResponseDto<String> refreshCommonCodeCache() {
    commonCodeCacheManager.refreshCommonCodeCache();
    return ApiResponseDto.ok("공통코드 캐시가 갱신되었습니다.");
  }

  @Operation(summary = "캐시 상태 확인", description = "Redis에 캐시된 공통코드 개수를 확인합니다.")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "캐시 상태 조회 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = Integer.class))),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @GetMapping("/cache/status")
  public ApiResponseDto<Integer> getCommonCodeCacheStatus() {
    int count = commonCodeCacheManager.getCachedCommonCodeCount();
    return ApiResponseDto.ok(count);
  }
}
