package gc.mda.kcg.domain.analysis;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

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

/**
 * vessel_analysis_results 읽기 전용 Repository.
 */
public interface VesselAnalysisRepository
        extends JpaRepository<VesselAnalysisResult, Long>, JpaSpecificationExecutor<VesselAnalysisResult> {

    /**
     * 특정 선박의 최신 분석 결과.
     */
    Optional<VesselAnalysisResult> findTopByMmsiOrderByAnalyzedAtDesc(String mmsi);

    /**
     * 특정 선박의 분석 이력 (시간 범위).
     */
    List<VesselAnalysisResult> findByMmsiAndAnalyzedAtAfterOrderByAnalyzedAtDesc(
            String mmsi, OffsetDateTime after);

    /**
     * 다크 베셀 목록 (최근 분석 결과, MMSI 중복 제거).
     */
    @Query("""
            SELECT v FROM VesselAnalysisResult v
            WHERE v.isDark = true AND v.analyzedAt > :after
            AND v.analyzedAt = (
                SELECT MAX(v2.analyzedAt) FROM VesselAnalysisResult v2
                WHERE v2.mmsi = v.mmsi AND v2.analyzedAt > :after
            )
            ORDER BY v.riskScore DESC
            """)
    Page<VesselAnalysisResult> findLatestDarkVessels(
            @Param("after") OffsetDateTime after, Pageable pageable);

    /**
     * 환적 의심 목록 (최근 분석 결과, MMSI 중복 제거).
     */
    @Query("""
            SELECT v FROM VesselAnalysisResult v
            WHERE v.transshipSuspect = true AND v.analyzedAt > :after
            AND v.analyzedAt = (
                SELECT MAX(v2.analyzedAt) FROM VesselAnalysisResult v2
                WHERE v2.mmsi = v.mmsi AND v2.analyzedAt > :after
            )
            ORDER BY v.riskScore DESC
            """)
    Page<VesselAnalysisResult> findLatestTransshipSuspects(
            @Param("after") OffsetDateTime after, Pageable pageable);
}
