-- 020_dashboard_flag_config.sql
-- Per-module dashboard flag settings (docs/2026-07-28-dashboard-redesign.md)
--
-- Which flags a module raises, and the numbers inside them, are client
-- decisions in the same way the ECD and completion dates are: one client wants
-- stale at 14 days, another at 60; one does not care about ECD churn at all.
-- Migration 019 made the dates configurable; this does the same for the rules
-- that read them.
--
-- An absent row means "enabled, with the registry's default thresholds". That
-- matters twice over: the dashboard works before anything has been configured,
-- and a flag added to the registry later is live everywhere without needing a
-- backfill or a config step. Only a deliberate change writes a row here.
--
-- thresholds is jsonb keyed by the threshold names the flag declares in
-- dashboardFlagRegistry() — {"days": 30} for the stale flag, {"moves": 3,
-- "days": 90} for the moving one. Unknown keys are ignored on read and
-- rejected on save, so a renamed threshold degrades to its default rather than
-- silently changing what a flag means.
--
-- No foreign key on flag_key: the registry lives in PHP, not in a table.
-- Constraining it here would mean a migration every time a flag is added,
-- which is the opposite of the point.

CREATE TABLE IF NOT EXISTS public.dashboard_flag_config (
    module        varchar(50)  NOT NULL,
    flag_key      varchar(50)  NOT NULL,
    enabled       boolean      NOT NULL DEFAULT true,
    thresholds    jsonb,
    updated_at    timestamptz  NOT NULL DEFAULT now(),
    updated_user  integer,

    CONSTRAINT dashboard_flag_config_pk
        PRIMARY KEY (module, flag_key)
);

COMMENT ON TABLE public.dashboard_flag_config IS
    'Per-module dashboard flag settings. An absent row means enabled with registry defaults, so the dashboard works unconfigured and newly added flags are live without a backfill. See docs/2026-07-28-dashboard-redesign.md.';

COMMENT ON COLUMN public.dashboard_flag_config.thresholds IS
    'jsonb keyed by the threshold names the flag declares in dashboardFlagRegistry(), e.g. {"moves": 3, "days": 90}. Unknown keys are ignored.';
