#!/bin/bash
# ============================================
# Switchboard Core - Database Bootstrap
# ============================================
# Idempotent: safe to run on every CI build.
# Creates the app role and database if they
# don't exist. Runs as the Postgres superuser.
#
# Required env vars:
#   PGHOST, PGPORT, PGUSER, PGPASSWORD  — admin connection
#   APP_USER, APP_PASSWORD               — app-level credentials
#   DB_NAME                              — target database name
# ============================================

set -euo pipefail

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Database bootstrap: ${DB_NAME}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# ── 1. Create role if not exists ─────────────
ROLE_EXISTS=$(psql -tAc "SELECT 1 FROM pg_roles WHERE rolname = '${APP_USER}';" postgres)

if [[ "${ROLE_EXISTS}" == "1" ]]; then
    echo "✓ Role '${APP_USER}' already exists"
    # Update password in case it changed
    psql -c "ALTER ROLE ${APP_USER} WITH PASSWORD '${APP_PASSWORD}';" postgres
    echo "✓ Password synced"
else
    psql -c "CREATE ROLE ${APP_USER} WITH LOGIN PASSWORD '${APP_PASSWORD}';" postgres
    echo "✓ Role '${APP_USER}' created"
fi

# ── 2. Create database if not exists ─────────
DB_EXISTS=$(psql -tAc "SELECT 1 FROM pg_database WHERE datname = '${DB_NAME}';" postgres)

if [[ "${DB_EXISTS}" == "1" ]]; then
    echo "✓ Database '${DB_NAME}' already exists"
else
    psql -c "CREATE DATABASE ${DB_NAME} OWNER ${APP_USER};" postgres
    echo "✓ Database '${DB_NAME}' created"
fi

# ── 3. Ensure extensions (requires superuser) ─
psql -d "${DB_NAME}" <<'SQL'
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
CREATE EXTENSION IF NOT EXISTS "vector";
SQL
echo "✓ Extensions verified (uuid-ossp, pgcrypto, vector)"

# ── 4. Grant privileges ─────────────────────
psql -d "${DB_NAME}" -c "GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} TO ${APP_USER};"
psql -d "${DB_NAME}" -c "GRANT ALL PRIVILEGES ON SCHEMA public TO ${APP_USER};"
psql -d "${DB_NAME}" -c "ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO ${APP_USER};"
psql -d "${DB_NAME}" -c "ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO ${APP_USER};"
echo "✓ Privileges granted"

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Bootstrap complete: ${DB_NAME}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
