#!/usr/bin/env bash
#
# Deploy a Supabase Edge Function to the prod self-hosted stack.
# Uploads `supabase/functions/<name>/` to
# `${PROD_SUPABASE_DIR}/volumes/functions/<name>/` and restarts the
# edge-runtime container so it picks up the new code.
#
# Usage:
#   ./scripts/prod/push-edge-function.sh <function-name>
#   ./scripts/prod/push-edge-function.sh mint-livekit-token

set -euo pipefail

here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${here}/config.sh"

name="${1:-}"
if [[ -z "${name}" ]]; then
  echo "usage: $0 <function-name>" >&2
  exit 1
fi

repo_root="$(cd "${here}/../.." && pwd)"
local_dir="${repo_root}/supabase/functions/${name}"

if [[ ! -d "${local_dir}" ]]; then
  echo "function dir not found: ${local_dir}" >&2
  exit 1
fi

remote_dir="${PROD_SUPABASE_DIR}/volumes/functions/${name}"

echo "syncing ${local_dir} → ${SSH_HOST}:${remote_dir}"
remote "mkdir -p ${remote_dir}"
# shellcheck disable=SC2086
scp ${SSH_OPTS} -r "${local_dir}/." "${SSH_HOST}:${remote_dir}/"

echo
echo "restarting edge-runtime"
remote "cd ${PROD_SUPABASE_DIR} && docker compose up -d functions"
remote "cd ${PROD_SUPABASE_DIR} && docker compose logs functions --tail=10"

echo
echo "done — function '${name}' deployed."
