-- t-paliad-212 — Slice 2a of CalDAV multi-calendar.
--
-- Adds paliad.caldav_sync_log.binding_id so the per-tick sync log
-- records which binding the entry belongs to. NULL for legacy rows
-- and for "global" log entries that aren't per-binding (Slice 2a
-- still writes one row per user per tick — Slice 2b's sync rewrite
-- moves to one row per (user, binding) per tick).
--
-- FK uses ON DELETE SET NULL so deleting a binding doesn't blow away
-- its historical sync log (audit trail wins over referential tidiness).
--
-- Idempotent: column added via DO block with information_schema check.

SELECT set_config(
    'paliad.audit_reason',
    'mig 107: add caldav_sync_log.binding_id for per-binding sync log entries (t-paliad-212 Slice 2a)',
    true);

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
         WHERE table_schema = 'paliad'
           AND table_name = 'caldav_sync_log'
           AND column_name = 'binding_id'
    ) THEN
        ALTER TABLE paliad.caldav_sync_log
            ADD COLUMN binding_id uuid
                REFERENCES paliad.user_calendar_bindings(id) ON DELETE SET NULL;
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS caldav_sync_log_binding_idx
    ON paliad.caldav_sync_log (binding_id, occurred_at DESC)
    WHERE binding_id IS NOT NULL;

-- Assertion: column exists and is nullable.
DO $$
DECLARE
    col_nullable text;
BEGIN
    SELECT is_nullable INTO col_nullable
      FROM information_schema.columns
     WHERE table_schema = 'paliad'
       AND table_name = 'caldav_sync_log'
       AND column_name = 'binding_id';
    IF col_nullable IS NULL THEN
        RAISE EXCEPTION 'mig 107 assertion failed: caldav_sync_log.binding_id missing';
    END IF;
    IF col_nullable <> 'YES' THEN
        RAISE EXCEPTION 'mig 107 assertion failed: caldav_sync_log.binding_id is NOT NULL (must be nullable)';
    END IF;
END $$;
