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

log() { echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] $*"; }
fail() { echo "ERROR: $*" >&2; exit 1; }

: "${DB_HOST:?DB_HOST required}"
: "${DB_PORT:?DB_PORT required}"
: "${DB_NAME:?DB_NAME required}"
: "${DB_USER:?DB_USER required}"
: "${DB_PASS:?DB_PASS required}"

export PGPASSWORD="$DB_PASS"

log "Ensuring pgvector extension exists in database '$DB_NAME'"

# Verify DB exists and is reachable
if ! psql -U "$DB_USER" -h "$DB_HOST" -p "$DB_PORT" -d "$DB_NAME" -tAc "SELECT 1" >/dev/null 2>&1; then
  fail "Unable to connect to database '$DB_NAME'. Ensure it exists and credentials are valid."
fi

psql -U "$DB_USER" -h "$DB_HOST" -p "$DB_PORT" -d "$DB_NAME" -v ON_ERROR_STOP=1 -c "CREATE EXTENSION IF NOT EXISTS vector;"

log "pgvector extension ensured (CREATE EXTENSION IF NOT EXISTS vector)."