#!/usr/bin/env bash
# vocal-email-forwarder installer
# Usage (depuis le compte Cloudflare cible, wrangler deja connecte) :
#   curl -fsSL https://packages.vocal.ch/vocal-email-forwarder/install.sh | bash -s -- --token=inst_XXXX
#
# Le token inst_* est genere une seule fois dans adm.vocal.ch (Inbox - Cles email).

set -euo pipefail

PACKAGES_BASE="${VOCAL_PACKAGES_URL:-https://packages.vocal.ch}"
API_BASE="${VOCAL_API_URL:-https://api.vocal.ch}"
INSTALL_TOKEN=""
SKIP_DEPLOY=0

usage() {
  cat <<EOF
Vocal Email Forwarder - installation

Usage:
  curl -fsSL https://packages.vocal.ch/vocal-email-forwarder/install.sh | bash -s -- --token=inst_XXXX

Options:
  --token=inst_xxx     Token d'installation (obligatoire, genere dans adm.vocal.ch)
  --skip-deploy        Ne pas lancer wrangler deploy (telecharge + provision seulement)

Prerequis:
  - Node.js 18+
  - wrangler connecte sur le compte Cloudflare cible (wrangler login)
  - unzip

Apres installation:
  Cloudflare Dashboard > Email > Email Routing > route > Send to Worker: vocal-email-forwarder
EOF
  exit 1
}

for arg in "$@"; do
  case "$arg" in
    --token=*) INSTALL_TOKEN="${arg#*=}" ;;
    --skip-deploy) SKIP_DEPLOY=1 ;;
    -h|--help) usage ;;
    *) echo "Option inconnue: $arg"; usage ;;
  esac
done

[[ -n "$INSTALL_TOKEN" ]] || usage

need_cmd() {
  command -v "$1" >/dev/null 2>&1 || { echo "Erreur: '$1' requis"; exit 1; }
}
need_cmd curl
need_cmd unzip
need_cmd node
need_cmd npm

if [[ "$SKIP_DEPLOY" -eq 0 ]]; then
  if ! command -v wrangler >/dev/null 2>&1; then
    echo ">> wrangler absent, installation locale..."
    npm install -g wrangler
  fi
fi

json_field() {
  node -e "const j=JSON.parse(require('fs').readFileSync(0,'utf8')); const k=process.argv[1]; const v=k.split('.').reduce((o,x)=>o&&o[x],j); if(v==null) process.exit(2); process.stdout.write(String(v));" "$1"
}

echo ">> Provision Vocal (cle ingest + metadata package)..."
PROVISION=$(curl -fsSL -X POST "${API_BASE}/api/packages/email-forwarder/provision" \
  -H "Authorization: Bearer ${INSTALL_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{}' ) || { echo "Erreur provision (token invalide, expire ou deja utilise ?)"; exit 1; }

PACKAGE_URL=$(printf '%s' "$PROVISION" | json_field package_url) || PACKAGE_URL=$(printf '%s' "$PROVISION" | json_field package_url_latest)
INGEST_KEY=$(printf '%s' "$PROVISION" | json_field key)
WORKER_NAME=$(printf '%s' "$PROVISION" | json_field worker_name || true)
WORKER_NAME="${WORKER_NAME:-vocal-email-forwarder}"

echo "   Package: $PACKAGE_URL"
echo "   Cle ingest: ${INGEST_KEY:0:16}..."

WORKDIR=$(mktemp -d)
trap 'rm -rf "$WORKDIR"' EXIT

echo ">> Telechargement du package..."
curl -fsSL "$PACKAGE_URL" -o "$WORKDIR/pkg.zip"
unzip -q "$WORKDIR/pkg.zip" -d "$WORKDIR"
cd "$WORKDIR/vocal-email-forwarder"

echo ">> npm install..."
npm install --omit=dev

if [[ "$SKIP_DEPLOY" -eq 0 ]]; then
  echo ">> wrangler deploy..."
  npx wrangler deploy

  echo ">> wrangler secret put INBOX_INGEST_KEY..."
  printf '%s' "$INGEST_KEY" | npx wrangler secret put INBOX_INGEST_KEY
else
  echo ">> skip-deploy: cle a configurer manuellement:"
  echo "   printf '%s' '${INGEST_KEY}' | npx wrangler secret put INBOX_INGEST_KEY"
fi

echo ">> Test connexion API Vocal..."
TEST=$(curl -fsSL -X POST "${API_BASE}/api/inbox/email/test" \
  -H "Authorization: Bearer ${INGEST_KEY}" \
  -H "Content-Type: application/json" \
  -d '{}' ) || { echo "Test echoue"; printf '%s\n' "$TEST"; exit 1; }

TEST_OK=$(printf '%s' "$TEST" | json_field success || echo false)
if [[ "$TEST_OK" != "true" ]]; then
  echo "Test echoue:"; printf '%s\n' "$TEST"; exit 1
fi

echo ""
echo "=========================================="
echo " Installation reussie"
echo "=========================================="
printf '%s\n' "$TEST" | node -e "
const j=JSON.parse(require('fs').readFileSync(0,'utf8'));
console.log(' Worker       :', '${WORKER_NAME}');
console.log(' Conversation :', j.conversation_id || '-');
console.log(' Message      :', j.message_id || '-');
console.log(' Domaines     :', (j.allowed_domains||[]).join(', '));
"
echo ""
echo "Etape manuelle restante:"
echo "  Cloudflare Dashboard > Email > Email Routing"
echo "  Creer une route (ex: support@votredomaine.ch) -> Send to Worker -> ${WORKER_NAME}"
echo ""
echo "Revocation cle: adm.vocal.ch > Inbox - Cles email > Revoquer"
