package incheon.ags.mrb.analysis.web;

import incheon.ags.mrb.analysis.service.AnalysisHistoryService;
import incheon.ags.mrb.analysis.vo.AnlsHstryJoinVO;
import incheon.com.cmm.api.DefaultApiResponse;
import incheon.com.security.vo.LoginVO;
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 lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "분석 이력 API")
@RestController
@RequestMapping("/ags/mrb/analysis")
@RequiredArgsConstructor
public class AnalysisHistoryController {

    private static final Logger logger = LoggerFactory.getLogger(AnalysisHistoryController.class);
    
    private final AnalysisHistoryService analysisHistoryService;

    /**
     * 분석이력 조회 API
     */
    @Operation(summary = "분석이력 조회", description = "현재 로그인한 사용자의 분석이력을 조회합니다.")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "분석이력 조회 성공",
                    content = @Content(schema = @Schema(implementation = DefaultApiResponse.class))),
            @ApiResponse(responseCode = "400", description = "요청 파라미터 오류"),
            @ApiResponse(responseCode = "500", description = "서버 내부 오류")
    })
    @GetMapping("/history")
    public ResponseEntity<DefaultApiResponse<List<AnlsHstryJoinVO>>> getAnalysisHistory(
            @RequestParam(defaultValue = "0") int offset,
            @RequestParam(defaultValue = "100") int limit,
            @RequestParam(required = false) String analysisType,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "DESC") String sortOrder,
            Authentication authentication) {

        logger.info("분석이력 조회 요청 - offset: {}, limit: {}, analysisType: {}, status: {}, sortOrder: {}",
                    offset, limit, analysisType, status, sortOrder);
        try {
            // 현재 접속한 사용자 ID 설정
            String currentUserId = "system";
            if (authentication != null) {
                LoginVO loginVO = (LoginVO) authentication.getPrincipal();
                currentUserId = loginVO.getUserId();
            }

            String normalizedSortOrder = (sortOrder == null) ? "DESC" : sortOrder.trim().toUpperCase();
            if (!"ASC".equals(normalizedSortOrder) && !"DESC".equals(normalizedSortOrder)) {
                throw new IllegalArgumentException("정렬 순서는 ASC 또는 DESC 값만 허용됩니다.");
            }

            List<AnlsHstryJoinVO> historyList = analysisHistoryService.getAnalysisHistory(
                currentUserId, offset, limit, analysisType, status, normalizedSortOrder);

            int totalCount = analysisHistoryService.getAnalysisHistoryCount(
                currentUserId, analysisType, status);

            return ResponseEntity.ok(
                DefaultApiResponse.success(historyList, "분석이력 조회 성공")
                    .addMeta("totalCount", totalCount)
            );
        } catch (IllegalArgumentException e) {
            logger.warn("분석이력 조회 실패 - 잘못된 요청: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(DefaultApiResponse.error(400, "분석이력 조회 실패 - 잘못된 요청", "INVALID_REQUEST"));
        } catch (SecurityException e) {
            logger.warn("분석이력 조회 실패 - 권한 없음: {}", e.getMessage());
            return ResponseEntity.status(403)
                    .body(DefaultApiResponse.error(403, "분석이력 조회 실패 - 권한 없음", "ACCESS_DENIED"));
        } catch (Exception e) {
            logger.error("분석이력 조회 실패 - 서버 오류: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError()
                    .body(DefaultApiResponse.error(500, "서버 내부 오류가 발생했습니다.", "SERVER_ERROR"));
        }
    }

    /**
     * 분석이력 삭제 API
     */
    @Operation(summary = "분석이력 삭제", description = "특정 분석이력을 삭제합니다.")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "삭제 성공",
                    content = @Content(schema = @Schema(implementation = DefaultApiResponse.class))),
            @ApiResponse(responseCode = "400", description = "요청 파라미터 오류"),
            @ApiResponse(responseCode = "404", description = "이력을 찾을 수 없음"),
            @ApiResponse(responseCode = "500", description = "서버 내부 오류")
    })
    @DeleteMapping("/history/{historyId}")
    public ResponseEntity<DefaultApiResponse<Void>> deleteAnalysisHistory(
            @PathVariable("historyId") int historyId,
            Authentication authentication) {

        logger.info("분석이력 삭제 요청 - historyId: {}", historyId);
        try {
            // 현재 접속한 사용자 ID 설정
            String currentUserId = "system";
            if (authentication != null) {
                LoginVO loginVO = (LoginVO) authentication.getPrincipal();
                currentUserId = loginVO.getUserId();
            }

            analysisHistoryService.deleteAnalysisHistory(currentUserId, historyId);

            return ResponseEntity.ok(
                    DefaultApiResponse.success(null, "삭제 성공")
            );
        } catch (IllegalArgumentException e) {
            logger.warn("분석이력 삭제 실패 - 잘못된 요청: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(DefaultApiResponse.error(400, "분석이력 삭제 실패 - 잘못된 요청", "INVALID_REQUEST"));
        } catch (SecurityException e) {
            logger.warn("분석이력 삭제 실패 - 권한 없음: {}", e.getMessage());
            return ResponseEntity.status(403)
                    .body(DefaultApiResponse.error(403, "분석이력 삭제 실패 - 권한 없음", "ACCESS_DENIED"));
        } catch (Exception e) {
            logger.error("분석이력 삭제 실패 - 서버 오류: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError()
                    .body(DefaultApiResponse.error(500, "서버 내부 오류가 발생했습니다.", "SERVER_ERROR"));
        }
    }
}