-- 빠른 Invalid Geometry 확인

-- 1. t_vessel_tracks_5min에 실제로 invalid geometry가 있는가?
SELECT
    '5min table - invalid count' as check_type,
    COUNT(*) as invalid_count
FROM signal.t_vessel_tracks_5min
WHERE track_geom IS NOT NULL
  AND NOT public.ST_IsValid(track_geom);

-- 2. 어떤 invalid 이유인가?
SELECT
    '5min table - invalid reasons' as check_type,
    public.ST_IsValidReason(track_geom) as reason,
    COUNT(*) as count
FROM signal.t_vessel_tracks_5min
WHERE track_geom IS NOT NULL
  AND NOT public.ST_IsValid(track_geom)
GROUP BY public.ST_IsValidReason(track_geom);

-- 3. 실제 invalid 샘플 확인
SELECT
    '5min table - invalid samples' as check_type,
    sig_src_cd,
    target_id,
    time_bucket,
    public.ST_NPoints(track_geom) as point_count,
    public.ST_AsText(track_geom) as wkt,
    public.ST_IsValidReason(track_geom) as reason
FROM signal.t_vessel_tracks_5min
WHERE track_geom IS NOT NULL
  AND NOT public.ST_IsValid(track_geom)
LIMIT 5;

-- 4. 에러 발생한 선박 확인 (vessel 000001_###0000072)
SELECT
    'Problem vessel check' as check_type,
    sig_src_cd,
    target_id,
    time_bucket,
    public.ST_NPoints(track_geom) as point_count,
    public.ST_IsValid(track_geom) as is_valid,
    public.ST_IsValidReason(track_geom) as reason,
    public.ST_AsText(track_geom) as wkt
FROM signal.t_vessel_tracks_5min
WHERE sig_src_cd = '000001'
  AND target_id LIKE '%0000072'
  AND time_bucket >= CURRENT_TIMESTAMP - INTERVAL '1 day'
ORDER BY time_bucket DESC
LIMIT 10;
