-- 0007_agent_config_versions.sql — versioned history of `AGENT_CONFIG`
-- payloads for Studio's Config dinámica screen (V11).
-- Spec: docs/arquitectura/componentes/11-stackbone-studio.md §"Mapa de pantallas / C.Config dinámica".
-- Task: docs/tasks/Studio V11 - Config dinámica.md (V11#01).
-- ADR:  docs/arquitectura/decisiones/2026-05-03-stackbone-studio-datapath-y-scope-mvp.md §D2/D7.
--
-- The current config is the row with the highest `version`. Older rows are
-- kept for the rollback action and the lateral history list. Hot-reload is
-- driven off `pg_notify('stackbone_platform_events', …)` from an INSERT trigger
-- — the local emulator orchestrator (V11#04) and `apps/api` SSE handlers
-- LISTEN on the same channel as the rest of the platform events.
--
-- `created_by_email` carries free text on the local emulator (no `user`
-- table inside the agent's Postgres) and the cloud control plane backfills
-- it via better-auth lookup. This mirrors `stackbone_platform.secrets` so the
-- audit shape stays uniform across vault screens.

CREATE TABLE IF NOT EXISTS stackbone_platform.agent_config_versions (
    id                  uuid        PRIMARY KEY DEFAULT gen_random_uuid(),
    -- Monotonically increasing per install. The application layer assigns
    -- `MAX(version) + 1` inside the same transaction as the INSERT so the
    -- column doubles as a stable cursor for the lateral history list.
    version             integer     NOT NULL CHECK (version >= 1),
    value               jsonb       NOT NULL,
    -- When a row originates from a rollback we record the source version
    -- so the UI can render "rolled back from v7" without joining twice.
    rolled_back_from    integer,
    created_by_email    text,
    created_at          timestamptz NOT NULL DEFAULT now()
);

CREATE UNIQUE INDEX IF NOT EXISTS agent_config_versions_version_idx
    ON stackbone_platform.agent_config_versions (version);

CREATE INDEX IF NOT EXISTS agent_config_versions_created_at_idx
    ON stackbone_platform.agent_config_versions (created_at DESC, version DESC);

CREATE OR REPLACE FUNCTION stackbone_platform.notify_agent_config_event() RETURNS trigger
LANGUAGE plpgsql AS $fn$
DECLARE
    payload jsonb;
BEGIN
    payload := jsonb_build_object(
        'type', 'agent_config.changed',
        'version', NEW.version,
        'rolled_back_from', NEW.rolled_back_from,
        'created_at', NEW.created_at
    );
    PERFORM pg_notify('stackbone_platform_events', payload::text);
    RETURN NULL;
END;
$fn$;

DROP TRIGGER IF EXISTS agent_config_versions_notify_aiu ON stackbone_platform.agent_config_versions;
CREATE TRIGGER agent_config_versions_notify_aiu
AFTER INSERT ON stackbone_platform.agent_config_versions
FOR EACH ROW EXECUTE FUNCTION stackbone_platform.notify_agent_config_event();
