#!/bin/bash
# Deploy ligbox-onboard-agents — Spec 037 Fase B
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="$SCRIPT_DIR/onboard"
TOKEN_FILE="$ROOT/secrets/cloudflare-wrangler.token"

if [[ ! -f "$TOKEN_FILE" ]]; then
  echo "Crie $TOKEN_FILE com o API token (uma linha, cfat_...)"
  echo "Dashboard: Manage Account > API Tokens > ligbox-wrangler-onboard-agents"
  exit 1
fi

export CLOUDFLARE_API_TOKEN
CLOUDFLARE_API_TOKEN="$(tr -d '[:space:]' < "$TOKEN_FILE")"

echo "Verificando token..."
curl -sf "https://api.cloudflare.com/client/v4/user/tokens/verify" \
  -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | grep -q '"success":true' \
  || { echo "Token inválido ou sem permissão verify"; exit 1; }
echo "Token OK"

cd "$ROOT"
if [[ ! -d node_modules ]]; then
  npm install
fi
npm run deploy
echo ""
echo "Deploy concluído. Teste:"
echo "  curl https://ligbox-onboard-agents.<subdominio-workers>.workers.dev/health"
echo "Depois configure rota agents.ligbox.com.br no dashboard ou wrangler.toml"
