#!/bin/bash
# Idempotent database setup script for stock-data-backend
# Creates PostgreSQL user and database if they don't exist, then runs migrations.
# Safe to run multiple times.
#
# Usage:
#   chmod +x deploy/setup_db.sh
#   ./deploy/setup_db.sh
#
# Customize these via environment variables:
#   DB_NAME=stock_data_backend DB_USER=stock_backend DB_PASS=changeme ./deploy/setup_db.sh

set -e

DB_NAME="${DB_NAME:-stock_data_backend}"
DB_USER="${DB_USER:-stock_backend}"
DB_PASS="${DB_PASS:-changeme}"

echo "Setting up database: ${DB_NAME} with user: ${DB_USER}"

# Create role and database if they don't exist
sudo -u postgres psql <<EOF
DO \$\$
BEGIN
  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${DB_USER}') THEN
    CREATE ROLE ${DB_USER} WITH LOGIN PASSWORD '${DB_PASS}';
    RAISE NOTICE 'Created role ${DB_USER}';
  ELSE
    RAISE NOTICE 'Role ${DB_USER} already exists';
  END IF;
END \$\$;

SELECT 'CREATE DATABASE ${DB_NAME} OWNER ${DB_USER}'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '${DB_NAME}')\gexec

GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} TO ${DB_USER};
EOF

echo "Database setup complete. Running migrations..."

# Run Alembic migrations
alembic upgrade head

echo "Migrations complete."
