import type { Migration } from '@/shared/db';

/**
 * Outbox — the write-to queue triage drops replies into. Unlike the generic
 * `<module>_send_queue` tables (fixed action/payload shape), the outbox needs
 * first-class `priority` and `not_before` columns so the Mac client can drain
 * "highest priority that is due" with an index, plus channel + delivery
 * bookkeeping for true (not optimistic) status.
 */
export const outboxMigrations: readonly Migration[] = [
  {
    id: '2026-06-28_outbox_initial',
    sql: `
      CREATE TABLE IF NOT EXISTS macsync.outbox (
        id             UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        device_id      UUID NOT NULL REFERENCES macsync.devices(id) ON DELETE CASCADE,
        recipient      TEXT NOT NULL,
        body           TEXT NOT NULL,
        -- Numeric weight (higher = sooner); derived from the scheduler's label.
        priority       INTEGER NOT NULL DEFAULT 0,
        channel_pref   TEXT NOT NULL DEFAULT 'auto',   -- auto | imessage | sms
        channel_used   TEXT,                           -- imessage | sms (set on send)
        not_before     TIMESTAMPTZ NOT NULL DEFAULT now(),
        status         TEXT NOT NULL DEFAULT 'queued', -- queued|sending|sent|delivered|failed
        attempts       INTEGER NOT NULL DEFAULT 0,
        max_attempts   INTEGER NOT NULL DEFAULT 3,
        error          TEXT,
        dedupe_key     TEXT,
        schedule_reason TEXT,
        created_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
        updated_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
        sent_at        TIMESTAMPTZ
      );
      -- Drain order: the Mac polls "due, highest priority, oldest first".
      CREATE INDEX IF NOT EXISTS idx_outbox_drain
        ON macsync.outbox (status, priority DESC, not_before ASC);
      -- Dedupe: never double-send the same logical reply (e.g. a triage re-run).
      CREATE UNIQUE INDEX IF NOT EXISTS ux_outbox_dedupe
        ON macsync.outbox (device_id, dedupe_key) WHERE dedupe_key IS NOT NULL;
    `,
  },
  {
    // Handoff 04: when set, marking this reply sent also marks the recipient's
    // conversation read (logical-read model — see entities/conversation-read).
    id: '2026-06-28_outbox_mark_read_on_send',
    sql: `
      ALTER TABLE macsync.outbox
        ADD COLUMN IF NOT EXISTS mark_read_on_send BOOLEAN NOT NULL DEFAULT false;
    `,
  },
];
