#!/usr/bin/env bash
#
# Insert a new signup-invite code into prod Supabase. Runs `INSERT INTO
# public.invites ...` via `docker exec psql`. Code is validated by the
# `handle_new_user` trigger when a new user registers.
#
# Usage:
#   ./scripts/prod/create-invite.sh <code> [<uses_limit>] [<expires_days>]
#   ./scripts/prod/create-invite.sh FRIENDS 20 365
#
# Defaults: uses_limit=50, expires_days=365

set -euo pipefail

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

code="${1:-}"
uses_limit="${2:-50}"
expires_days="${3:-365}"

if [[ -z "${code}" ]]; then
  echo "usage: $0 <code> [<uses_limit>=50] [<expires_days>=365]" >&2
  exit 1
fi

if [[ ${#code} -lt 4 || ${#code} -gt 64 ]]; then
  echo "code length must be between 4 and 64 chars (got ${#code})" >&2
  exit 1
fi

sql="INSERT INTO public.invites (code, uses_limit, expires_at, disabled) \
VALUES ('${code}', ${uses_limit}, now() + interval '${expires_days} days', false) \
RETURNING code, uses_limit, expires_at;"

echo "creating invite '${code}' (uses=${uses_limit}, expires=${expires_days}d)"
remote "cd ${PROD_SUPABASE_DIR} && docker compose exec -T db psql -U postgres -d postgres -c \"${sql}\""
