-- 0005_stackbone_viewer.sql — read-only role for the Studio DB Explorer.
-- Spec: docs/arquitectura/componentes/11-stackbone-studio.md §"DB Explorer".
-- Task: docs/tasks/Studio V6 - DB Explorer read-only.md (V6#01).
-- ADR:  docs/arquitectura/decisiones/2026-05-03-stackbone-studio-datapath-y-scope-mvp.md §D6.
--
-- The role is `NOLOGIN` because callers (apps/api, apps/cli emulator) reach it
-- via `SET ROLE stackbone_viewer` on a session opened with the regular owner
-- credentials, not by logging in as `stackbone_viewer` directly. This keeps the
-- Neon HTTP driver one-shot model (D3) untouched: the connection string still
-- belongs to the owner, the privilege drop happens per-statement.
--
-- DEFAULT PRIVILEGES are scoped to the current migration runner (`current_user`)
-- so any table the runner creates afterwards in `public`, `stackbone_platform`,
-- and the future `pgmq` / `rag_*` schemas auto-grants SELECT to the viewer
-- without re-issuing GRANTs from a follow-up migration.

DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'stackbone_viewer') THEN
        CREATE ROLE stackbone_viewer NOLOGIN;
    END IF;
END
$$;

-- Existing schemas at the time this migration runs.
GRANT USAGE ON SCHEMA public           TO stackbone_viewer;
GRANT USAGE ON SCHEMA stackbone_platform  TO stackbone_viewer;

GRANT SELECT ON ALL TABLES    IN SCHEMA public          TO stackbone_viewer;
GRANT SELECT ON ALL TABLES    IN SCHEMA stackbone_platform TO stackbone_viewer;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public          TO stackbone_viewer;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA stackbone_platform TO stackbone_viewer;

-- Default privileges so any *future* table created by the migration runner in
-- these schemas auto-grants SELECT to `stackbone_viewer`. The Studio sidebar
-- promises visibility into `pgmq.*`, `_storage_objects`, `rag_*` and the
-- creator's own schemas — without these defaults, every new table created by
-- a downstream migration (or by the agent itself via Drizzle) would silently
-- be invisible to the DB Explorer.
ALTER DEFAULT PRIVILEGES IN SCHEMA public
    GRANT SELECT ON TABLES    TO stackbone_viewer;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
    GRANT SELECT ON SEQUENCES TO stackbone_viewer;
ALTER DEFAULT PRIVILEGES IN SCHEMA stackbone_platform
    GRANT SELECT ON TABLES    TO stackbone_viewer;
ALTER DEFAULT PRIVILEGES IN SCHEMA stackbone_platform
    GRANT SELECT ON SEQUENCES TO stackbone_viewer;
