#!/bin/bash
# =================================================================
# Partner API v2 — Core Flow Verification Script
# Usage: ./partner-api-verify.sh [BASE_URL]
# Default: http://localhost:8081
# =================================================================

BASE="${1:-http://localhost:8081}"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

pass=0
fail=0
skip=0

check() {
  local label="$1" method="$2" path="$3" expected="$4" body="$5"
  local url="${BASE}${path}"
  local auth_header=""
  [ -n "$TOKEN" ] && auth_header="-H \"Authorization: $TOKEN\""

  if [ "$method" = "GET" ]; then
    resp=$(eval curl -s -o /dev/null -w '%{http_code}' "$auth_header" "$url" 2>/dev/null)
  else
    resp=$(eval curl -s -o /dev/null -w '%{http_code}' -X "$method" "$auth_header" \
      -H 'Content-Type: application/json' \
      ${body:+-d "'$body'"} "$url" 2>/dev/null)
  fi

  if [ "$resp" = "$expected" ]; then
    echo -e "  ${GREEN}[PASS]${NC} $label → $resp"
    ((pass++))
  else
    echo -e "  ${RED}[FAIL]${NC} $label → $resp (expected $expected)"
    ((fail++))
  fi
}

skip_check() {
  local label="$1"
  echo -e "  ${YELLOW}[SKIP]${NC} $label"
  ((skip++))
}

echo "========================================"
echo " Partner API v2 Verification"
echo " Base URL: $BASE"
echo "========================================"
echo ""

# ── 0. Health Check ──
echo "── 0. Health Check ──"
check "Ping" GET "/ping" "200"
echo ""

# ── 1. Auth ──
echo "── 1. Auth (Unauthenticated) ──"
check "Login (no body)" POST "/api/partner/auth/login" "400"
check "Forgot password (no body)" POST "/api/partner/auth/password/forgot" "400"
check "Reset password (no body)" POST "/api/partner/auth/password/reset" "400"
echo ""

# Login with test credentials
echo "── 1b. Auth (Login) ──"
echo "  Attempting login with test credentials..."
LOGIN_RESP=$(curl -s -X POST "${BASE}/api/partner/auth/login" \
  -H 'Content-Type: application/json' \
  -d '{"email":"test@test.com","password":"test1234"}' 2>/dev/null)

TOKEN=$(echo "$LOGIN_RESP" | grep -o '"accessToken":"[^"]*"' | cut -d'"' -f4)

if [ -n "$TOKEN" ]; then
  echo -e "  ${GREEN}[PASS]${NC} Login succeeded — token acquired"
  ((pass++))
else
  echo -e "  ${YELLOW}[INFO]${NC} Login failed (expected — use real credentials)"
  echo "         To test authenticated endpoints, export TOKEN=<your-token> first"
  echo "         Example:"
  echo "           export TOKEN=\$(curl -s -X POST ${BASE}/api/partner/auth/login \\"
  echo "             -H 'Content-Type: application/json' \\"
  echo "             -d '{\"email\":\"YOUR_EMAIL\",\"password\":\"YOUR_PW\"}' | jq -r '.accessToken')"
  echo ""
fi

if [ -z "$TOKEN" ]; then
  echo "── Skipping authenticated endpoints (no token) ──"
  echo ""
  skip_check "Dashboard Summary"
  skip_check "Dashboard Chart"
  skip_check "Deposits"
  skip_check "Deposit Sessions"
  skip_check "Withdrawals"
  skip_check "Balances"
  skip_check "Ledger"
  skip_check "Settlement Daily Fees"
  skip_check "Settlement Realizations"
  skip_check "Settlement Balance"
  skip_check "Gas Costs"
  skip_check "Gas Invoices"
  skip_check "Integration API Key"
  skip_check "Integration Webhook Logs"
  skip_check "Integration Telegram"
  skip_check "Account Profile"
  echo ""
else
  # ── 2. Dashboard ──
  echo "── 2. Dashboard ──"
  check "Summary" GET "/api/partner/dashboard/summary" "200"
  check "Chart (7 days)" GET "/api/partner/dashboard/chart?days=7" "200"
  echo ""

  # ── 3. Deposits ──
  echo "── 3. Deposits ──"
  check "Deposit List" GET "/api/partner/deposits?page=1&size=10" "200"
  check "Deposit Sessions" GET "/api/partner/deposit-sessions?page=1&size=10" "200"
  check "Payment Links" GET "/api/partner/payment-links?page=1&size=10" "200"
  check "Deposit Addresses" GET "/api/partner/deposit-addresses?page=1&size=10" "200"
  check "Collections" GET "/api/partner/collections?page=1&size=10" "200"
  check "Axim Payments" GET "/api/partner/axim-payments?page=1&size=10" "200"
  echo ""

  # ── 4. Withdrawals ──
  echo "── 4. Withdrawals ──"
  check "Withdrawal List" GET "/api/partner/withdrawals?page=1&size=10" "200"
  check "Whitelist" GET "/api/partner/withdrawals/whitelist" "200"
  echo ""

  # ── 5. Balance / Ledger ──
  echo "── 5. Balance / Ledger ──"
  check "Balances" GET "/api/partner/balances" "200"
  check "Ledger" GET "/api/partner/ledger?page=1&size=10" "200"
  echo ""

  # ── 6. Settlement ──
  echo "── 6. Settlement ──"
  check "Daily Fees" GET "/api/partner/settlement/daily-fees?page=1&size=10" "200"
  check "Realizations" GET "/api/partner/settlement/realizations?page=1&size=10" "200"
  check "Balance" GET "/api/partner/settlement/balance" "200"
  echo ""

  # ── 7. Gas ──
  echo "── 7. Gas Costs ──"
  check "Gas Costs" GET "/api/partner/gas-costs?page=1&size=10" "200"
  check "Gas Invoices" GET "/api/partner/gas-invoices?page=1&size=10" "200"
  echo ""

  # ── 8. Sub-Partners (DISTRIBUTOR only) ──
  echo "── 8. Sub-Partners (may 403 for MERCHANT) ──"
  check "Sub-Partner List" GET "/api/partner/sub-partners?page=1&size=10" "200"
  check "Sub-Partner Overview" GET "/api/partner/sub-partners/overview" "200"
  echo ""

  # ── 9. Reports (DISTRIBUTOR only) ──
  echo "── 9. Reports (may 403 for MERCHANT) ──"
  check "Revenue Report" GET "/api/partner/reports/revenue" "200"
  check "Fee Report" GET "/api/partner/reports/fees" "200"
  check "Performance Report" GET "/api/partner/reports/performance" "200"
  echo ""

  # ── 10. Integration ──
  echo "── 10. Integration ──"
  check "API Key" GET "/api/partner/integration/api-key" "200"
  check "Webhook Logs" GET "/api/partner/integration/webhook/logs?page=1&size=10" "200"
  check "Telegram Config" GET "/api/partner/integration/telegram" "200"
  check "Axim Settings" GET "/api/partner/integration/axim" "200"
  echo ""

  # ── 11. Account ──
  echo "── 11. Account ──"
  check "Profile" GET "/api/partner/account/profile" "200"
  check "2FA Setup" GET "/api/partner/account/2fa/setup" "200"
  echo ""

  # ── 12. Logout ──
  echo "── 12. Logout ──"
  check "Logout" POST "/api/partner/auth/logout" "200"
  echo ""
fi

# ── Summary ──
total=$((pass + fail + skip))
echo "========================================"
echo " Results: $pass passed / $fail failed / $skip skipped (total: $total)"
echo "========================================"
