-- 305_eid_schedule_views.sql
-- 이드 일정(schedule_brief, 미래 surface) 파생뷰 2. 신규 schedule 테이블 0 — events/events_history 재활용.
-- quadrant(중요×긴급)·D-N 정렬은 app 층(schedule overlay). 뷰는 raw 입력 필드 + today/defer 집계만.
-- CREATE VIEW 선례 = 010_soft_delete / 283_corpus_chunks. BEGIN/COMMIT 없음.
--
-- v_schedule_today: 오늘(Asia/Seoul local day) 활성 일정. active 필터 = events.py:list_today reference.
--   today 경계 = Seoul 자정→UTC 변환(date_trunc ... AT TIME ZONE 왕복). LATERAL 로 1회 계산.
-- v_schedule_defer_pattern: events_history change_kind IN(defer,reschedule) 를 event_id 별 COUNT.
--   '반복 미룸' 임계 3회+ (schedule overlay 판단근거 #5). reactivate 는 제외.

CREATE OR REPLACE VIEW v_schedule_today AS
SELECT e.id, e.user_id, e.title, e.kind, e.status, e.priority,
       e.due_at, e.start_at, e.end_at, e.started_at, e.defer_until, e.project_tag
FROM events e
CROSS JOIN LATERAL (
    SELECT (date_trunc('day', now() AT TIME ZONE 'Asia/Seoul') AT TIME ZONE 'Asia/Seoul') AS lo
) b
WHERE (e.status IN ('inbox','next','scheduled','in_progress')
       OR (e.status = 'deferred' AND e.defer_until IS NOT NULL AND e.defer_until <= now()))
  AND (
        (e.kind = 'task'           AND e.due_at     >= b.lo AND e.due_at     < b.lo + interval '1 day')
     OR (e.kind = 'calendar_event' AND e.start_at   >= b.lo AND e.start_at   < b.lo + interval '1 day')
     OR (e.kind = 'activity_log'   AND e.started_at >= b.lo AND e.started_at < b.lo + interval '1 day')
  );

CREATE OR REPLACE VIEW v_schedule_defer_pattern AS
SELECT eh.event_id,
       COUNT(*)::int       AS defer_reschedule_count,
       MAX(eh.changed_at)  AS last_changed_at,
       (COUNT(*) >= 3)     AS is_repeat_defer
FROM events_history eh
WHERE eh.change_kind IN ('defer','reschedule')
GROUP BY eh.event_id;
