#!/usr/bin/env bash
# Applies one or more SQL migration files to the Supabase database.
# Reads the connection string from .env.migrate (chmod 600, owner-only) so the
# DB password is never passed on the command line or echoed.
#
# Usage:  bash supabase/migrate.sh supabase/migrations/0004_foo.sql [more.sql ...]
set -euo pipefail

cd "$(dirname "$0")/.."

if [ ! -f .env.migrate ]; then
  echo "ERROR: .env.migrate not found. Create it with:" >&2
  echo "  SUPABASE_DB_URL=postgresql://postgres.<ref>:<password>@<host>:5432/postgres" >&2
  exit 1
fi

set -a
# shellcheck disable=SC1091
source .env.migrate
set +a

: "${SUPABASE_DB_URL:?SUPABASE_DB_URL not set in .env.migrate}"

if [ "$#" -eq 0 ]; then
  echo "ERROR: pass at least one .sql file to apply." >&2
  exit 1
fi

for f in "$@"; do
  echo "── applying $f"
  psql "$SUPABASE_DB_URL" -v ON_ERROR_STOP=1 -f "$f"
done

echo "✓ migrations applied"
