#!/usr/bin/env bash
# Phase D — terminal-only activation (browser POST is rejected)
#
#   export SLUG_BASE_URL=https://insfra.co/osh
#   export SLUG_API_KEY=<from step 3.3 finalize>
#   bash activate.sh

set -euo pipefail

BASE_URL="${SLUG_BASE_URL:-http://localhost:3000}"
BASE_URL="${BASE_URL%/}"
API_KEY="${SLUG_API_KEY:-}"
# Use /api/bridge/activate on shared hosting (some hosts block /api/activate)
ACT_API="${SLUG_ACTIVATE_API:-$BASE_URL/api/bridge/activate}"

echo "=== Phase D — terminal activation ==="
echo "Base:     $BASE_URL"
echo "Endpoint: $ACT_API"
echo ""

if [[ -z "$API_KEY" ]]; then
  echo "4.1 failed: export SLUG_API_KEY (from step 3.3 finalize)."
  exit 1
fi

echo "4.2 POST activate ..."
HTTP_CODE=$(curl -sS -o /tmp/slug-activate.json -w "%{http_code}" -X POST "$ACT_API" \
  -H "x-api-key: ${API_KEY}" \
  -H "x-slug-client: terminal" \
  -H "Content-Type: application/json" \
  -d "{\"apiKey\":\"${API_KEY}\"}")

RESULT=$(cat /tmp/slug-activate.json 2>/dev/null || true)
echo "$RESULT"
echo ""
echo "HTTP $HTTP_CODE"

if [[ "$HTTP_CODE" == "403" ]] && echo "$RESULT" | grep -qi "<!DOCTYPE html"; then
  echo ""
  echo "ERROR: Host firewall blocked this request (403 HTML, not JSON)."
  echo "  - Confirm SLUG_BASE_URL includes subfolder: https://your-domain.com/osh"
  echo "  - Try: export SLUG_ACTIVATE_API=\$SLUG_BASE_URL/api/bridge/activate"
  echo "  - Ask host to allow POST to /osh/api/bridge/activate"
  exit 1
fi

if echo "$RESULT" | grep -q '"deniedReason":"browser_activation_forbidden"'; then
  echo "ERROR: Missing x-slug-client: terminal header."
  exit 1
fi

if ! echo "$RESULT" | grep -q '"activated":true'; then
  echo "4.2 failed."
  if echo "$RESULT" | grep -q '"error"'; then
    echo "$RESULT" | sed -n 's/.*"error":"\([^"]*\)".*/Hint: \1/p'
  fi
  exit 1
fi

echo "4.3 Parse unlockUrl (e.g. jq -r .unlockUrl)"
if command -v jq >/dev/null 2>&1; then
  UNLOCK=$(echo "$RESULT" | jq -r '.unlockUrl // empty')
  SLUG=$(echo "$RESULT" | jq -r '.username // empty')
else
  UNLOCK=$(echo "$RESULT" | sed -n 's/.*"unlockUrl":"\([^"]*\)".*/\1/p' | sed 's#\\/#/#g')
  SLUG=$(echo "$RESULT" | sed -n 's/.*"username":"\([^"]*\)".*/\1/p')
fi

echo ""
echo "5.1 Open unlockUrl once in browser:"
[[ -n "$UNLOCK" ]] && echo "  $UNLOCK"
echo ""
echo "6.1 App entry:"
[[ -n "$SLUG" ]] && echo "  ${BASE_URL}/ea/${SLUG}/app/"
