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

usage() {
  cat <<'EOF'
Usage:
  SUPABASE_DB_URL='postgresql://...' ./scripts/pull-supabase-schema.sh [output_file]

Description:
  Dumps the current Supabase schema using pg_dump and writes it to a file.

Defaults:
  output_file: supabase/schema.sql
  SCHEMAS: public

Optional env vars:
  SCHEMAS           Comma-separated schemas to include (example: public,auth,storage)
  SUPABASE_DB_URL   Postgres connection URI from Supabase Database settings

Examples:
  SUPABASE_DB_URL='postgresql://postgres:***@db.xxx.supabase.co:5432/postgres?sslmode=require' \
    ./scripts/pull-supabase-schema.sh

  SCHEMAS='public,auth,storage' \
  SUPABASE_DB_URL='postgresql://postgres:***@db.xxx.supabase.co:5432/postgres?sslmode=require' \
    ./scripts/pull-supabase-schema.sh supabase/full-schema.sql
EOF
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

if ! command -v pg_dump >/dev/null 2>&1; then
  echo "Error: pg_dump is required but was not found."
  echo "Install PostgreSQL client tools (e.g. 'brew install postgresql@16')."
  exit 1
fi

if [[ -z "${SUPABASE_DB_URL:-}" ]]; then
  echo "Error: SUPABASE_DB_URL is not set."
  echo "Copy the Postgres connection string from Supabase:"
  echo "  Project Settings -> Database -> Connection string (URI)"
  usage
  exit 1
fi

OUTPUT_FILE="${1:-supabase/schema.sql}"
SCHEMAS_CSV="${SCHEMAS:-public}"
DB_URL="${SUPABASE_DB_URL}"

# Ensure SSL is required if it is not already present in the URI.
if [[ "${DB_URL}" != *"sslmode="* ]]; then
  if [[ "${DB_URL}" == *"?"* ]]; then
    DB_URL="${DB_URL}&sslmode=require"
  else
    DB_URL="${DB_URL}?sslmode=require"
  fi
fi

IFS=',' read -r -a RAW_SCHEMAS <<< "${SCHEMAS_CSV}"
SCHEMA_ARGS=()
for raw_schema in "${RAW_SCHEMAS[@]}"; do
  schema="$(printf "%s" "${raw_schema}" | tr -d '[:space:]')"
  if [[ -n "${schema}" ]]; then
    SCHEMA_ARGS+=(--schema="${schema}")
  fi
done

if [[ ${#SCHEMA_ARGS[@]} -eq 0 ]]; then
  echo "Error: no schemas selected. Set SCHEMAS to at least one schema name."
  exit 1
fi

mkdir -p "$(dirname "${OUTPUT_FILE}")"
tmp_file="$(mktemp)"
trap 'rm -f "${tmp_file}"' EXIT

pg_dump "${DB_URL}" \
  --schema-only \
  --no-owner \
  --no-privileges \
  "${SCHEMA_ARGS[@]}" \
  > "${tmp_file}"

{
  echo "-- Generated by scripts/pull-supabase-schema.sh"
  echo "-- Generated at: $(date -u +"%Y-%m-%dT%H:%M:%SZ")"
  echo "-- Schemas: ${SCHEMAS_CSV}"
  echo
  cat "${tmp_file}"
} > "${OUTPUT_FILE}"

echo "Schema dump written to ${OUTPUT_FILE}"
