#!/bin/bash

# Admin API Testing Script
# Generates admin token and tests chargeback endpoints

set -e

API_BASE="http://localhost:8000/api"
ADMIN_EMAIL="${1:-admin@showprima.com}"
ADMIN_PASSWORD="${2:-password}"

echo "🔑 Logging in as $ADMIN_EMAIL..."

# Login and extract token
LOGIN_RESPONSE=$(curl -s -X POST "$API_BASE/admin/login" \
  -H "Content-Type: application/json" \
  -d "{\"email\":\"$ADMIN_EMAIL\",\"password\":\"$ADMIN_PASSWORD\"}")

TOKEN=$(echo $LOGIN_RESPONSE | json_pp | grep '"token"' | head -1 | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
  echo "❌ Login failed!"
  echo $LOGIN_RESPONSE | json_pp
  exit 1
fi

echo "✅ Token generated successfully"
echo ""
echo "📋 Export this for manual testing:"
echo "export ADMIN_TOKEN='$TOKEN'"
echo ""

# Test /admin/me
echo "🧪 Testing /admin/me..."
curl -s -X GET "$API_BASE/admin/me" \
  -H "Authorization: Bearer $TOKEN" | json_pp | head -20
echo ""

# Test chargebacks list
echo "🧪 Testing /admin/financial/chargebacks..."
curl -s -X GET "$API_BASE/admin/financial/chargebacks" \
  -H "Authorization: Bearer $TOKEN" | json_pp
echo ""

# Test export with dates
echo "🧪 Testing /admin/financial/chargebacks/export..."
DATE_FROM=$(date -v-30d +%Y-%m-%d 2>/dev/null || date -d "30 days ago" +%Y-%m-%d)
DATE_TO=$(date +%Y-%m-%d)

echo "Date range: $DATE_FROM to $DATE_TO"
curl -s -X GET "$API_BASE/admin/financial/chargebacks/export?date_from=$DATE_FROM&date_to=$DATE_TO&format=json" \
  -H "Authorization: Bearer $TOKEN" | json_pp
echo ""

echo "✅ All tests complete!"
echo ""
echo "💡 Use this token for additional testing:"
echo "export ADMIN_TOKEN='$TOKEN'"
echo ""
echo "📝 Example curl commands:"
echo "curl -H \"Authorization: Bearer \$ADMIN_TOKEN\" $API_BASE/admin/financial/chargebacks"
echo "curl -H \"Authorization: Bearer \$ADMIN_TOKEN\" $API_BASE/admin/financial/chargebacks/analytics"
