-- Migration: mail_uid_scan_state
-- Adds incremental UID-scan state to mail_connections (Phase 2 performance).
--
-- Problem being solved:
--   scan-internal.post.ts fetched the last 200 messages per folder on EVERY trigger
--   (NOOP-tick every 2 minutes × folders × accounts = sustained CPU load 51-55%).
--   Phase 1 (in-flight guard) capped stacking. Phase 2 eliminates the root cost:
--   re-fetching already-seen messages.
--
-- New columns:
--   folder_scan_state JSONB:
--     Per-folder {lastUid, uidvalidity} map. On each scan run the daemon fetches
--     only UIDs > lastUid for each folder. After processing, lastUid is updated to
--     the highest UID seen.
--     UIDVALIDITY guard: if the server's uidValidity changed, lastUid is reset to 0
--     and a full 200-message sweep is performed for that folder (server renumbered UIDs).
--     Format: { "INBOX": {"lastUid":1234,"uidvalidity":5678}, "Junk Email": {...} }
--     DEFAULT '{}' → first run treats all folders as lastUid=0 (full sweep).
--
--   last_full_sweep_at TIMESTAMPTZ:
--     Timestamp of the last quality full-sweep (1×/day).
--     Guards against blocklist updates not reaching older messages.
--     NULL → no full-sweep yet → first run counts as full-sweep.
--
-- Breaking-change status: NONE.
--   DEFAULT '{}' covers all existing rows for folder_scan_state.
--   last_full_sweep_at is nullable → existing rows get NULL (triggers full-sweep on
--   next run, which is the correct and safe behavior: first run after migration
--   always does a full 200-message sweep per folder, exactly as before).
--
-- Deploy: pnpm prisma migrate deploy (on server via GitHub Actions pipeline)

ALTER TABLE "rebreak"."mail_connections"
  ADD COLUMN "folder_scan_state" JSONB        NOT NULL DEFAULT '{}',
  ADD COLUMN "last_full_sweep_at" TIMESTAMPTZ;

-- No index on folder_scan_state:
--   Accessed only by primary key lookup (per-connection read), not in WHERE clauses.
-- No index on last_full_sweep_at:
--   Checked in application logic after fetching the connection by id — not used in queries.
