-- One-time DBA setup for the brain vector store on postgres18.
--
-- Creates the `brain` database, the `brain_app` role, and the pgvector
-- extension. The ingestion service connects as brain_app and creates
-- the table + HNSW index idempotently at startup (see
-- internal/vectorstore.PGStore.Init).
--
-- Run from koala as the postgres superuser:
--
--   kubectl exec -n databases postgres18-0 -- \
--     psql -U postgres -f /tmp/brain-embeddings-init.sql
--
-- Or apply with:
--
--   PASSWORD='<sops-generated>' \
--   kubectl exec -i -n databases postgres18-0 -- \
--     psql -U postgres -v password="'$PASSWORD'" \
--     < scripts/brain-embeddings-init.sql
--
-- Idempotent: rerunning is safe.

\set ON_ERROR_STOP on

DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_database WHERE datname = 'brain') THEN
        CREATE DATABASE brain;
    END IF;
END
$$;

DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'brain_app') THEN
        EXECUTE format('CREATE ROLE brain_app LOGIN PASSWORD %L', :'password');
    END IF;
END
$$;

GRANT ALL PRIVILEGES ON DATABASE brain TO brain_app;

\c brain

CREATE EXTENSION IF NOT EXISTS vector;
GRANT ALL ON SCHEMA public TO brain_app;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO brain_app;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO brain_app;
