#!/usr/bin/env bash

set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
bundle_dir="$(cd "$script_dir/.." && pwd)"

compose() {
  if docker compose version >/dev/null 2>&1; then
    docker compose "$@"
  elif command -v docker-compose >/dev/null 2>&1; then
    docker-compose "$@"
  else
    echo "docker compose or docker-compose is required." >&2
    exit 1
  fi
}

ensure_env_file() {
  if [[ ! -f "$bundle_dir/.env" && -f "$bundle_dir/.env.example" ]]; then
    cp "$bundle_dir/.env.example" "$bundle_dir/.env"
    echo "Created .env from .env.example"
  fi
}

load_env() {
  set -a
  # shellcheck disable=SC1091
  source "$bundle_dir/.env"
  set +a
}

wait_for_postgres() {
  local attempt
  for attempt in {1..60}; do
    if compose exec -T postgres pg_isready -U "${POSTGRES_USER:-postgres}" -d postgres >/dev/null 2>&1; then
      return 0
    fi
    sleep 2
  done

  echo "Postgres is not ready after 120 seconds." >&2
  exit 1
}

wait_for_external_postgres() {
  local container_name="${EXTERNAL_POSTGRES_CONTAINER:-}"
  local attempt

  if [[ -z "$container_name" ]]; then
    echo "EXTERNAL_POSTGRES_CONTAINER is required when USE_EXTERNAL_INFRA=true and SKIP_DB_INIT is not true." >&2
    exit 1
  fi

  for attempt in {1..60}; do
    if docker exec "$container_name" pg_isready -U "${POSTGRES_USER:-postgres}" -d postgres >/dev/null 2>&1; then
      return 0
    fi
    sleep 2
  done

  echo "External Postgres is not ready after 120 seconds: $container_name" >&2
  exit 1
}

create_database_if_missing() {
  local db_name="$1"
  local exists

  exists="$(
    compose exec -T postgres psql -U "${POSTGRES_USER:-postgres}" -d postgres -tAc \
      "SELECT 1 FROM pg_database WHERE datname = '$db_name'" | tr -d '[:space:]'
  )"

  if [[ "$exists" == "1" ]]; then
    echo "Database already exists: $db_name"
    return 0
  fi

  echo "Creating database: $db_name"
  compose exec -T postgres createdb -U "${POSTGRES_USER:-postgres}" "$db_name"
}

create_external_database_if_missing() {
  local db_name="$1"
  local container_name="${EXTERNAL_POSTGRES_CONTAINER:-}"
  local exists

  exists="$(
    docker exec "$container_name" psql -U "${POSTGRES_USER:-postgres}" -d postgres -tAc \
      "SELECT 1 FROM pg_database WHERE datname = '$db_name'" | tr -d '[:space:]'
  )"

  if [[ "$exists" == "1" ]]; then
    echo "Database already exists: $db_name"
    return 0
  fi

  echo "Creating database: $db_name"
  docker exec "$container_name" createdb -U "${POSTGRES_USER:-postgres}" "$db_name"
}

databases=(
  pcp_ballistics
  pcp_requests
  pcp_route_processing
  pcp_missions
  pcp_slots
  pcp_complex_plan
  pcp_satellite_catalog
  pcp_stations
  pcp_tgu
  pcp_satellites
)

ensure_env_file
load_env

cd "$bundle_dir"
if [[ "${USE_EXTERNAL_INFRA:-false}" == "true" ]]; then
  wait_for_external_postgres

  for db_name in "${databases[@]}"; do
    create_external_database_if_missing "$db_name"
  done
else
  compose up -d postgres
  wait_for_postgres

  for db_name in "${databases[@]}"; do
    create_database_if_missing "$db_name"
  done
fi

echo "Database initialization completed. Tables are left to service Flyway migrations."
echo "No schema objects or seed data were created by this script."
