#!/usr/bin/env bash
set -euo pipefail

# dd0c init-db: creates per-product databases and runs migrations
# Usage: ./init-db.sh [postgres-url]

PG_URL="${1:-postgresql://dd0c:dd0c-dev@localhost:5432}"

DATABASES=(dd0c_route dd0c_drift dd0c_alert dd0c_portal dd0c_cost dd0c_run)

echo "Creating databases..."
for db in "${DATABASES[@]}"; do
  psql "$PG_URL/postgres" -tc "SELECT 1 FROM pg_database WHERE datname = '$db'" | grep -q 1 \
    || psql "$PG_URL/postgres" -c "CREATE DATABASE $db" 2>/dev/null
  echo "  ✓ $db"
done

echo ""
echo "Running migrations..."

PRODUCTS=(
  "01-llm-cost-router:dd0c_route"
  "02-iac-drift-detection/saas:dd0c_drift"
  "03-alert-intelligence:dd0c_alert"
  "04-lightweight-idp:dd0c_portal"
  "05-aws-cost-anomaly:dd0c_cost"
  "06-runbook-automation/saas:dd0c_run"
)

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

for entry in "${PRODUCTS[@]}"; do
  product="${entry%%:*}"
  db="${entry##*:}"
  migration_dir="$SCRIPT_DIR/$product/migrations"

  if [ -d "$migration_dir" ]; then
    for sql in "$migration_dir"/*.sql; do
      echo "  $db ← $(basename "$sql")"
      psql "$PG_URL/$db" -f "$sql" 2>/dev/null || echo "    (already applied or error)"
    done
  fi
done

echo ""
echo "Done. All databases ready."
