-- Migration 976: Platform-wide runtime settings (v1.0.4)
-- Replaces in-memory maintenance toggle with a DB-backed key/value table so
-- all pods see the same state. Values are typed to avoid string-parsing in
-- the hot path.

CREATE TABLE IF NOT EXISTS public.platform_settings (
    id              SERIAL PRIMARY KEY,
    key             TEXT NOT NULL UNIQUE,
    value_bool      BOOLEAN,
    value_text      TEXT,
    description     TEXT NOT NULL DEFAULT '',
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_by      UUID REFERENCES public.users(id) ON DELETE SET NULL
);

CREATE INDEX IF NOT EXISTS idx_platform_settings_key ON public.platform_settings(key);

-- Seed the maintenance_mode row; idempotent so rerunning migrations is safe.
INSERT INTO public.platform_settings (key, value_bool, description)
VALUES ('maintenance_mode', FALSE, 'When TRUE, all API requests outside the exempt list return 503.')
ON CONFLICT (key) DO NOTHING;
