-- Migration 000004: Feature flags (Sprint 5 — E3-09)
-- Per-tenant (or global) feature flags stored in PostgreSQL.
-- Toggle via admin API; read by the application with Redis-backed caching.

CREATE TABLE feature_flags (
    id          UUID        PRIMARY KEY DEFAULT uuid_generate_v4(),
    -- tenant_id NULL means a global flag that applies to all tenants.
    tenant_id   UUID        REFERENCES tenants(id) ON DELETE CASCADE,
    name        TEXT        NOT NULL,
    is_enabled  BOOLEAN     NOT NULL DEFAULT FALSE,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    -- A flag name must be unique per tenant (or globally when tenant_id is NULL).
    UNIQUE NULLS NOT DISTINCT (tenant_id, name)
);

-- Auto-update updated_at on row modification.
CREATE TRIGGER feature_flags_updated_at
    BEFORE UPDATE ON feature_flags
    FOR EACH ROW EXECUTE FUNCTION set_updated_at();

-- ──────────────────────────────────────────────
-- Default global flags
-- ──────────────────────────────────────────────
-- ner_enabled: controls whether the NER layer runs in the PII pipeline.
-- Disabling it speeds up low-sensitivity requests at the cost of recall.
INSERT INTO feature_flags (tenant_id, name, is_enabled)
VALUES (NULL, 'ner_enabled', TRUE);
