-- 0006_secrets.sql — local mirror of `installation_secret` for the
-- `stackbone dev` emulator (Studio V10).
-- Spec: docs/arquitectura/componentes/11-stackbone-studio.md §"Secrets".
-- Task: docs/tasks/Studio V10 - Secrets.md (V10#02).
-- ADR:  docs/arquitectura/decisiones/2026-05-03-stackbone-studio-datapath-y-scope-mvp.md
--       (decision V10#01 in the task itself: cloud secrets stay in
--       `installation_secret` of the control plane; local emulator stores
--       the same wire shape here so the Studio UI sees identical data.)
--
-- The emulator runs without a control plane. To keep the Studio Secrets
-- screen wire-compatible (one shape from `@stackbone/validators`) we mirror
-- the cloud table inside `stackbone_platform.secrets`. Encryption uses the
-- documented `dev-only-encryption-key` (see STUDIO_LOCAL_DEV_ENCRYPTION_KEY
-- in libs/validators) and never leaves the developer machine.
--
-- `is_system` carries the same semantics as in cloud — the saga injects
-- nothing here so the column stays at its default `false`, but we keep it
-- for parity in case future system-level injectors land in the emulator.

CREATE TABLE IF NOT EXISTS stackbone_platform.secrets (
    id              uuid        PRIMARY KEY DEFAULT gen_random_uuid(),
    name            text        NOT NULL,
    version         text        NOT NULL DEFAULT 'v1' CHECK (version IN ('v1')),
    nonce           bytea       NOT NULL,
    ciphertext      bytea       NOT NULL,
    is_system       boolean     NOT NULL DEFAULT false,
    description     text,
    -- created_by_email is a free-text field in local: there is no `user`
    -- table in the emulator's Postgres. The cloud surface backfills the
    -- equivalent via better-auth user lookup.
    created_by_email text,
    created_at      timestamptz NOT NULL DEFAULT now(),
    updated_at      timestamptz NOT NULL DEFAULT now()
);

CREATE UNIQUE INDEX IF NOT EXISTS secrets_name_idx
    ON stackbone_platform.secrets (name);
