package com.kamco.cd.training.dataset;

import com.kamco.cd.training.config.api.ApiResponseDto;
import com.kamco.cd.training.dataset.dto.DatasetClsObjDto;
import com.kamco.cd.training.dataset.dto.DatasetDto;
import com.kamco.cd.training.dataset.service.DatasetClsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
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.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@Tag(name = "분류모델 학습데이터 관리", description = "어드민 홈 > 학습데이터관리 > 분류데이터셋")
@RestController
@RequestMapping("/api/datasets/cls")
@RequiredArgsConstructor
public class DatasetClsApiController {

  private final DatasetClsService datasetClsService;

  @Operation(summary = "분류 학습데이터 관리 목록 조회", description = "분류 학습데이터 목록을 조회합니다.")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "조회 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = Page.class))),
        @ApiResponse(responseCode = "400", description = "잘못된 검색 조건", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @GetMapping
  public ApiResponseDto<Page<DatasetDto.Basic>> searchDatasets(
      @Parameter(
              description = "구분",
              example = "",
              schema = @Schema(allowableValues = {"DELIVER", "PRODUCTION"}))
          @RequestParam(required = false)
          String dataType,
      @Parameter(description = "제목", example = "") @RequestParam(required = false) String title,
      @Parameter(description = "페이지 번호 (0부터 시작)", example = "0") @RequestParam(defaultValue = "0")
          int page,
      @Parameter(description = "페이지 크기", example = "20") @RequestParam(defaultValue = "20")
          int size) {
    DatasetDto.SearchReq searchReq = new DatasetDto.SearchReq();
    searchReq.setTitle(title);
    searchReq.setDataType(dataType);
    searchReq.setPage(page);
    searchReq.setSize(size);
    return ApiResponseDto.ok(datasetClsService.searchDatasets(searchReq));
  }

  @Operation(summary = "학습데이터관리 상세 조회", description = "학습데이터관리 상세 정보를 조회합니다.")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "조회 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = DatasetDto.Basic.class))),
        @ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @GetMapping("/{uuid}")
  public ApiResponseDto<DatasetDto.Basic> getDatasetDetail(@PathVariable UUID uuid) {
    return ApiResponseDto.ok(datasetClsService.getDatasetDetail(uuid));
  }

  @Operation(summary = "학습데이터 수정", description = "학습데이터 제목, 메모 수정")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            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("/{uuid}")
  public ApiResponseDto<UUID> updateDataset(
      @PathVariable UUID uuid, @RequestBody DatasetDto.UpdateReq updateReq) {
    datasetClsService.updateDataset(uuid, updateReq);
    return ApiResponseDto.ok(uuid);
  }

  @Operation(summary = "학습데이터 삭제", description = "학습데이터를 삭제합니다.(납품 데이터는 삭제 불가)")
  @ApiResponses(
      value = {
        @ApiResponse(responseCode = "201", description = "삭제 성공", content = @Content),
        @ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content),
        @ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @DeleteMapping("/{uuid}")
  public ApiResponseDto<UUID> deleteDatasets(@PathVariable UUID uuid) {

    datasetClsService.deleteDatasets(uuid);
    return ApiResponseDto.ok(uuid);
  }

  @Operation(summary = "분류 학습데이터 관리 목록 조회", description = "분류 학습데이터 목록을 조회합니다.")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "조회 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = Page.class))),
        @ApiResponse(responseCode = "400", description = "잘못된 검색 조건", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @GetMapping("/obj-list")
  public ApiResponseDto<Page<DatasetClsObjDto.Basic>> searchDatasetObjectList(
      @Parameter(description = "회차 uuid", example = "edf3812d-4558-4134-ad5f-5cd9dc78a1da")
          @RequestParam(required = true)
          UUID uuid,
      @Parameter(description = "년도", example = "") @RequestParam(required = false) Integer yyyy,
      @Parameter(description = "분류", example = "") @RequestParam(required = false) String classCd,
      @Parameter(description = "도엽번호", example = "") @RequestParam(required = false)
          String mapSheetNum,
      @RequestParam(defaultValue = "0") int page,
      @RequestParam(defaultValue = "20") int size) {
    DatasetClsObjDto.ClsSearchReq searchReq = new DatasetClsObjDto.ClsSearchReq();
    searchReq.setUuid(uuid);
    searchReq.setYyyy(yyyy);
    searchReq.setClassCd(classCd);
    searchReq.setMapSheetNum(mapSheetNum);
    searchReq.setPage(page);
    searchReq.setSize(size);
    return ApiResponseDto.ok(datasetClsService.searchDatasetClsObjectList(searchReq));
  }

  @Operation(summary = "학습데이터 zip파일 등록", description = "학습데이터 zip파일 등록 합니다.")
  @PostMapping
  public ApiResponseDto<ApiResponseDto.ResponseObj> insertDataset(
      @RequestBody @Valid DatasetDto.AddReq addReq) {

    return ApiResponseDto.okObject(datasetClsService.insertDataset(addReq));
  }

  @Operation(summary = "분류데이터셋 객체별 파일 Path 조회", description = "파일 Path 조회")
  @GetMapping("/files")
  public ResponseEntity<Resource> getFile(@RequestParam UUID uuid) throws Exception {

    String path = datasetClsService.getFilePathByUUIDPathTif(uuid);
    return datasetClsService.getFilePathByFile(path);
  }
}
