#!/usr/bin/env bash
# Verify the Node API responds locally (run on the server after deploy).
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# shellcheck source=lib/node-env-port.sh
source "$ROOT/scripts/lib/node-env-port.sh"

API_PORT="$(node_env_port "$ROOT")"
BASE="http://127.0.0.1:${API_PORT}"

printf 'Checking API at %s (node/.env PORT=%s)\n' "$BASE" "$API_PORT"

code="$(curl -sS -o /tmp/calendar-health.json -w '%{http_code}' "${BASE}/v1/health" || echo 000)"
if [[ "$code" != "200" ]]; then
  echo "FAIL: GET ${BASE}/v1/health → HTTP $code" >&2
  echo "  pm2 logs calendar-api --lines 50" >&2
  echo "  Check PORT in node/.env and: sudo bash scripts/configure-apache.sh" >&2
  exit 1
fi

echo "OK: /v1/health → HTTP $code"
cat /tmp/calendar-health.json
echo

if [[ $# -ge 2 ]]; then
  user="$1"
  slug="$2"
  path="${BASE}/v1/public/${user}/${slug}"
  code="$(curl -sS -o /tmp/calendar-public.json -w '%{http_code}' "$path" || echo 000)"
  if [[ "$code" != "200" ]]; then
    echo "FAIL: GET $path → HTTP $code" >&2
    head -c 500 /tmp/calendar-public.json >&2 || true
    echo >&2
    exit 1
  fi
  echo "OK: /v1/public/${user}/${slug} → HTTP $code"
fi
