package gc.mda.kcg.domain.analysis;

import gc.mda.kcg.permission.annotation.RequirePermission;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.time.OffsetDateTime;
import java.util.List;

/**
 * vessel_analysis_results 직접 조회 API.
 * prediction이 kcgaidb에 저장한 분석 결과를 프론트엔드에 직접 제공.
 * 기존 iran proxy와 별도 경로 (/api/analysis/*).
 */
@RestController
@RequestMapping("/api/analysis")
@RequiredArgsConstructor
public class VesselAnalysisController {

    private final VesselAnalysisService service;

    /**
     * 분석 결과 목록 조회 (필터 + 페이징).
     * 기본: 최근 1시간 내 결과.
     */
    @GetMapping("/vessels")
    @RequirePermission(resource = "detection:dark-vessel", operation = "READ")
    public Page<VesselAnalysisResponse> listVessels(
            @RequestParam(required = false) String mmsi,
            @RequestParam(required = false) String zoneCode,
            @RequestParam(required = false) String riskLevel,
            @RequestParam(required = false) Boolean isDark,
            @RequestParam(defaultValue = "1") int hours,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "50") int size
    ) {
        OffsetDateTime after = OffsetDateTime.now().minusHours(hours);
        return service.getAnalysisResults(
                mmsi, zoneCode, riskLevel, isDark, after,
                PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "analyzedAt"))
        ).map(VesselAnalysisResponse::from);
    }

    /**
     * 특정 선박 최신 분석 결과 (features 포함).
     */
    @GetMapping("/vessels/{mmsi}")
    @RequirePermission(resource = "detection:dark-vessel", operation = "READ")
    public VesselAnalysisResponse getLatest(@PathVariable String mmsi) {
        return VesselAnalysisResponse.from(service.getLatestByMmsi(mmsi));
    }

    /**
     * 특정 선박 분석 이력 (기본 24시간).
     */
    @GetMapping("/vessels/{mmsi}/history")
    @RequirePermission(resource = "detection:dark-vessel", operation = "READ")
    public List<VesselAnalysisResponse> getHistory(
            @PathVariable String mmsi,
            @RequestParam(defaultValue = "24") int hours
    ) {
        return service.getHistory(mmsi, hours).stream()
                .map(VesselAnalysisResponse::from)
                .toList();
    }

    /**
     * 다크 베셀 목록 (최신 분석, MMSI 중복 제거).
     */
    @GetMapping("/dark")
    @RequirePermission(resource = "detection:dark-vessel", operation = "READ")
    public Page<VesselAnalysisResponse> listDarkVessels(
            @RequestParam(defaultValue = "1") int hours,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "50") int size
    ) {
        return service.getDarkVessels(hours,
                PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "riskScore"))
        ).map(VesselAnalysisResponse::from);
    }

    /**
     * 환적 의심 목록 (최신 분석, MMSI 중복 제거).
     */
    @GetMapping("/transship")
    @RequirePermission(resource = "detection:dark-vessel", operation = "READ")
    public Page<VesselAnalysisResponse> listTransshipSuspects(
            @RequestParam(defaultValue = "1") int hours,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "50") int size
    ) {
        return service.getTransshipSuspects(hours,
                PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "riskScore"))
        ).map(VesselAnalysisResponse::from);
    }
}
