#!/usr/bin/env bash
# TW-296 — Staging smoke: unauth tools → 401; Bearer Lucos JWT → named userId.
# Usage:
#   ACCESS_TOKEN=<lucos-jwt> BASE_URL=https://stagingapi.lucos.com ./scripts/verify-mcp-tunnel-auth.sh
# Optional: EXPECT_USER_ID=<userId>
set -euo pipefail

BASE_URL="${BASE_URL:-http://localhost:3007}"
BASE_URL="${BASE_URL%/}"
TOOLS_URL="${BASE_URL}/api/v1/tools"

echo "==> Unauthenticated GET ${TOOLS_URL} (expect 401)"
UNAUTH_CODE="$(curl -s -o /dev/null -w '%{http_code}' "${TOOLS_URL}")"
if [[ "${UNAUTH_CODE}" != "401" ]]; then
  echo "FAIL: expected 401, got ${UNAUTH_CODE}"
  exit 1
fi
echo "OK: ${UNAUTH_CODE}"

if [[ -z "${ACCESS_TOKEN:-}" ]]; then
  echo "==> ACCESS_TOKEN not set; skipping authenticated check"
  echo "    Obtain token via ChatGPT MCP OAuth or POST ${BASE_URL}/api/v1/auth/mcp/token"
  echo "PASS (partial): unauthenticated deny verified"
  exit 0
fi

echo "==> Authenticated GET ${TOOLS_URL}"
RESP="$(curl -s -w '\n%{http_code}' "${TOOLS_URL}" -H "Authorization: Bearer ${ACCESS_TOKEN}")"
BODY="$(echo "${RESP}" | sed '$d')"
CODE="$(echo "${RESP}" | tail -n1)"

if [[ "${CODE}" != "200" ]]; then
  echo "FAIL: expected 200, got ${CODE}"
  echo "${BODY}"
  exit 1
fi

echo "${BODY}"
USER_ID="$(echo "${BODY}" | node -e "let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>{try{console.log(JSON.parse(d).userId||'')}catch{console.log('')}}")"
if [[ -z "${USER_ID}" ]]; then
  echo "FAIL: response missing userId"
  exit 1
fi

if [[ -n "${EXPECT_USER_ID:-}" && "${USER_ID}" != "${EXPECT_USER_ID}" ]]; then
  echo "FAIL: expected userId=${EXPECT_USER_ID}, got ${USER_ID}"
  exit 1
fi

echo "OK: named identity userId=${USER_ID}"
echo "PASS: tunnel auth handoff to api.lucos.com tools smoke"
