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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SERVICE_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
SCHEMA_FILE="${SCRIPT_DIR}/bootstrap-lightweight-schema.sql"

if [ -f "${SERVICE_DIR}/.env" ]; then
  # shellcheck disable=SC1090
  set -a && source "${SERVICE_DIR}/.env" && set +a
fi

if [ -z "${DATABASE_URL:-}" ]; then
  echo "DATABASE_URL is required. Set it in ${SERVICE_DIR}/.env or export it before running." >&2
  exit 1
fi

echo "Applying lightweight token-aggregation schema using ${SCHEMA_FILE}"
psql "${DATABASE_URL}" -v ON_ERROR_STOP=1 -f "${SCHEMA_FILE}"
