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

# PostgreSQL connection settings. Override via env if needed:
#   PGHOST=... PGPORT=... PGUSER=... PGPASSWORD=... ./create_pcp_databases.sh
PGHOST="${PGHOST:-localhost}"
PGPORT="${PGPORT:-5432}"
PGUSER="${PGUSER:-postgres}"
PGPASSWORD="${PGPASSWORD:-password}"
export PGPASSWORD

DATABASES=(
  pcp_ballistics
  pcp_complex_plan
  pcp_missions
  pcp_requests
  pcp_satellite_catalog
  pcp_satellites
  pcp_slots
  pcp_stations
  pcp_tgu
  pcp_tle
)

# Services whose migrations use PostGIS geometry/extension.
POSTGIS_DATABASES=(
  pcp_ballistics
  pcp_missions
  pcp_requests
  pcp_slots
  pcp_stations
)

psql_admin() {
  psql -v ON_ERROR_STOP=1 \
    --host="$PGHOST" \
    --port="$PGPORT" \
    --username="$PGUSER" \
    --dbname=postgres \
    "$@"
}

psql_db() {
  local db="$1"
  shift
  psql -v ON_ERROR_STOP=1 \
    --host="$PGHOST" \
    --port="$PGPORT" \
    --username="$PGUSER" \
    --dbname="$db" \
    "$@"
}

create_database_if_missing() {
  local db="$1"
  local exists
  exists="$(psql_admin -tAc "SELECT 1 FROM pg_database WHERE datname = '$db'")"
  if [[ "$exists" == "1" ]]; then
    echo "Database already exists: $db"
  else
    echo "Creating database: $db"
    psql_admin -c "CREATE DATABASE \"$db\" OWNER \"$PGUSER\" ENCODING 'UTF8';"
  fi
}

enable_postgis_if_possible() {
  local db="$1"
  echo "Enabling PostGIS in database: $db"
  psql_db "$db" -c "CREATE EXTENSION IF NOT EXISTS postgis;"
}

main() {
  echo "Target PostgreSQL: ${PGHOST}:${PGPORT}, user=${PGUSER}"

  for db in "${DATABASES[@]}"; do
    create_database_if_missing "$db"
  done

  for db in "${POSTGIS_DATABASES[@]}"; do
    enable_postgis_if_possible "$db"
  done

  echo "Done. Databases are ready. Services will create their schemas via Flyway on startup."
}

main "$@"
