-- t-paliad-212 — Slice 2c of CalDAV multi-calendar.
--
-- Adds the MKCALENDAR-capability tri-state to paliad.user_caldav_config:
--   * supports_mkcalendar = NULL    → unprobed (probe runs lazily on
--                                     the first /api/caldav-discover or
--                                     /api/caldav-mkcalendar call).
--   * supports_mkcalendar = TRUE    → server accepts MKCALENDAR; the
--                                     "Create new calendar" affordance
--                                     in the picker is visible.
--   * supports_mkcalendar = FALSE   → Google-style degrade; UI hides the
--                                     create button and surfaces the
--                                     "create it in your provider's UI"
--                                     notice with a manual-URL input.
-- The probed_at timestamp lets us re-probe stale-cached results when
-- the user changes credentials (SaveConfig invalidates by SetNull in
-- the Go service layer; the column is here so the next round of
-- probing has somewhere to land).
--
-- Idempotent (column-exists DO block) + assertion at the bottom.

SELECT set_config(
    'paliad.audit_reason',
    'mig 108: add user_caldav_config.supports_mkcalendar tri-state for t-paliad-212 Slice 2c capability probe',
    true);

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
         WHERE table_schema = 'paliad'
           AND table_name = 'user_caldav_config'
           AND column_name = 'supports_mkcalendar'
    ) THEN
        ALTER TABLE paliad.user_caldav_config
            ADD COLUMN supports_mkcalendar boolean;
    END IF;
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
         WHERE table_schema = 'paliad'
           AND table_name = 'user_caldav_config'
           AND column_name = 'mkcalendar_probed_at'
    ) THEN
        ALTER TABLE paliad.user_caldav_config
            ADD COLUMN mkcalendar_probed_at timestamptz;
    END IF;
END $$;

-- Assertion — both columns present and nullable.
DO $$
DECLARE
    sup_nullable text;
    probed_nullable text;
BEGIN
    SELECT is_nullable INTO sup_nullable
      FROM information_schema.columns
     WHERE table_schema = 'paliad' AND table_name = 'user_caldav_config'
       AND column_name = 'supports_mkcalendar';
    SELECT is_nullable INTO probed_nullable
      FROM information_schema.columns
     WHERE table_schema = 'paliad' AND table_name = 'user_caldav_config'
       AND column_name = 'mkcalendar_probed_at';
    IF sup_nullable <> 'YES' OR probed_nullable <> 'YES' THEN
        RAISE EXCEPTION
            'mig 108 assertion failed: expected both columns nullable, got supports=% probed=%',
            sup_nullable, probed_nullable;
    END IF;
END $$;
