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

if [[ -n "${AI_GATEWAY_PG_CONTAINER:-}" ]]; then
  CONTAINER="$AI_GATEWAY_PG_CONTAINER"
elif docker inspect easyai-pgvector >/dev/null 2>&1; then
  CONTAINER="easyai-pgvector"
elif docker inspect postgres >/dev/null 2>&1; then
  CONTAINER="postgres"
else
  CONTAINER="easyai-pgvector"
fi
PGUSER="${AI_GATEWAY_PG_USER:-easyai}"
DB_NAME="${AI_GATEWAY_DATABASE_NAME:-easyai_ai_gateway}"

version_num="$(
  docker exec "$CONTAINER" \
    psql -U "$PGUSER" -d postgres -tAc "SHOW server_version_num" \
    | tr -d '[:space:]'
)"

if [[ "${version_num:-0}" -lt 180000 ]]; then
  echo "[ai-gateway] warning: PostgreSQL 18 is expected, current server_version_num=${version_num}"
fi

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

if [[ "$exists" == "1" ]]; then
  echo "[ai-gateway] database already exists: ${DB_NAME}"
  exit 0
fi

docker exec "$CONTAINER" \
  psql -U "$PGUSER" -d postgres -c "CREATE DATABASE \"${DB_NAME}\""

echo "[ai-gateway] database created: ${DB_NAME}"
