#!/bin/bash
set -e

# Create per-product databases
for db in dd0c_route dd0c_drift dd0c_alert dd0c_portal dd0c_cost dd0c_run; do
  echo "Creating database: $db"
  psql -v ON_ERROR_STOP=0 --username "$POSTGRES_USER" --dbname postgres -c "CREATE DATABASE $db;" 2>/dev/null || true
done

# Run migrations for each product
run_migrations() {
  local db=$1
  local dir=$2
  if [ -d "$dir" ]; then
    for sql in "$dir"/*.sql; do
      [ -f "$sql" ] || continue
      echo "  $db ← $(basename $sql)"
      psql -v ON_ERROR_STOP=0 --username "$POSTGRES_USER" --dbname "$db" -f "$sql" 2>/dev/null || true
    done
  fi
}

run_migrations dd0c_alert /migrations/03-alert
run_migrations dd0c_portal /migrations/04-portal
run_migrations dd0c_cost /migrations/05-cost
run_migrations dd0c_run /migrations/06-run

echo "All databases initialized."
