#!/usr/bin/env bash
# Create the QuantEngine database and application role on the local PostgreSQL instance.

set -euo pipefail

DB_NAME="${DB_NAME:-quantenginedb}"
DB_USER="${DB_USER:-quantengine_app}"
DB_PASSWORD="${DB_PASSWORD:-CHANGE_ME}"
DB_HOST="${DB_HOST:-127.0.0.1}"
DB_PORT="${DB_PORT:-5432}"
ADMIN_DB="${ADMIN_DB:-postgres}"
SCHEMA_NAME="${SCHEMA_NAME:-quantengine}"

echo "Creating database and role for ${DB_NAME}..."
sudo -u postgres psql -h "${DB_HOST}" -p "${DB_PORT}" -d "${ADMIN_DB}" -v ON_ERROR_STOP=1 <<SQL
DO \$\$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${DB_USER}') THEN
        CREATE ROLE ${DB_USER} LOGIN PASSWORD '${DB_PASSWORD}';
    ELSE
        ALTER ROLE ${DB_USER} WITH LOGIN PASSWORD '${DB_PASSWORD}';
    END IF;
END
\$\$;

DO \$\$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_database WHERE datname = '${DB_NAME}') THEN
        CREATE DATABASE ${DB_NAME} OWNER ${DB_USER};
    END IF;
END
\$\$;
SQL

sudo -u postgres psql -h "${DB_HOST}" -p "${DB_PORT}" -d "${DB_NAME}" -v ON_ERROR_STOP=1 <<SQL
CREATE SCHEMA IF NOT EXISTS ${SCHEMA_NAME} AUTHORIZATION ${DB_USER};
GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} TO ${DB_USER};
GRANT USAGE, CREATE ON SCHEMA ${SCHEMA_NAME} TO ${DB_USER};
ALTER SCHEMA ${SCHEMA_NAME} OWNER TO ${DB_USER};
SQL

APP_ENV_FILE="${APP_ENV_FILE:-/home/kjh2064/.config/quantengine.env}"

mkdir -p "$(dirname "${APP_ENV_FILE}")"
cat > "${APP_ENV_FILE}" <<EOF
ConnectionStrings__DefaultConnection=Host=127.0.0.1;Database=${DB_NAME};Username=${DB_USER};Password=${DB_PASSWORD};Search Path=${SCHEMA_NAME};
EOF

chmod 600 "${APP_ENV_FILE}"

echo "Database setup completed: ${DB_NAME} / ${DB_USER}"
echo "Wrote app env file: ${APP_ENV_FILE}"
