#!/bin/bash
# sql/01-init-bugsink.sh
# ============================================================================
# BUGSINK DATABASE INITIALIZATION (ADR-015)
# ============================================================================
# This script creates the Bugsink database and user for error tracking.
# It runs after 00-init-extensions.sql due to alphabetical ordering.
#
# Note: Shell scripts in docker-entrypoint-initdb.d/ can execute multiple
# SQL commands including CREATE DATABASE (which requires a separate transaction).
# ============================================================================

set -e

# Use the postgres superuser to create the bugsink user and database
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    -- Create Bugsink user (if not exists)
    DO \$\$
    BEGIN
      IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'bugsink') THEN
        CREATE USER bugsink WITH PASSWORD 'bugsink_dev_password';
        RAISE NOTICE 'Created bugsink user';
      ELSE
        RAISE NOTICE 'Bugsink user already exists';
      END IF;
    END \$\$;
EOSQL

# Check if bugsink database exists, create if not
if psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" -lqt | cut -d \| -f 1 | grep -qw bugsink; then
    echo "Bugsink database already exists"
else
    psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
        CREATE DATABASE bugsink OWNER bugsink;
        GRANT ALL PRIVILEGES ON DATABASE bugsink TO bugsink;
EOSQL
    echo "Created bugsink database"
fi

echo "✅ Bugsink database and user have been configured (ADR-015)"
