#!/usr/bin/env bash
#
# tools/test-db.sh — garante o banco de teste dedicado (idempotente).
#
# Os testes usam `concordia_test` (ver phpunit.xml/CoreTestCase); NUNCA o banco de dev.
# Uso: tools/test-db.sh [nome-do-banco]
set -Eeuo pipefail

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

DB="${1:-concordia_test}"
USER="${DB_USERNAME:-concordia}"
# shellcheck source=tools/runtime.sh
. "$ROOT/tools/runtime.sh"
COMPOSE=("${ENGINE[@]}" compose -p "$(bash "$ROOT/tools/project-name.sh")" --env-file .env "${COMPOSE_FILES[@]}")

exists="$("${COMPOSE[@]}" exec -T postgres psql -U "$USER" -d postgres -tAc \
    "SELECT 1 FROM pg_database WHERE datname='${DB}'" 2>/dev/null | tr -d '[:space:]' || true)"

if [ "$exists" = "1" ]; then
    echo "test-db: '${DB}' já existe"
else
    "${COMPOSE[@]}" exec -T postgres psql -U "$USER" -d postgres -c "CREATE DATABASE \"${DB}\"" >/dev/null
    echo "test-db: '${DB}' criado"
fi
