#!/bin/bash
echo "🧪 Testing Login API with Cookie Handling..."
echo ""

# Create cookie jar
COOKIE_JAR="/tmp/mawidi-test-cookies.txt"
rm -f $COOKIE_JAR

# Get CSRF token (saves cookie)
echo "1️⃣ Fetching CSRF token..."
RESPONSE=$(curl -s -c $COOKIE_JAR http://localhost:9000/api/auth/csrf)
CSRF_TOKEN=$(echo "$RESPONSE" | jq -r .csrfToken)
echo "   Token: ${CSRF_TOKEN:0:20}..."
echo "   Cookie saved to: $COOKIE_JAR"
echo ""

# Test login (uses cookie)
echo "2️⃣ Testing login with credentials..."
LOGIN_RESPONSE=$(curl -s -b $COOKIE_JAR -c $COOKIE_JAR \
  -X POST http://localhost:9000/api/auth/login \
  -H "Content-Type: application/json" \
  -H "X-CSRF-Token: $CSRF_TOKEN" \
  -d '{"identifier": "realtest@mawidi.com", "password": "TestPassword123!@#"}')

echo "$LOGIN_RESPONSE" | jq
echo ""

# Check result
if echo "$LOGIN_RESPONSE" | jq -e '.success' > /dev/null 2>&1; then
  echo "✅ LOGIN SUCCESSFUL!"
  echo "   User: $(echo "$LOGIN_RESPONSE" | jq -r '.user.fullName')"
  echo "   Email: $(echo "$LOGIN_RESPONSE" | jq -r '.user.email')"
  echo "   Token received: $(echo "$LOGIN_RESPONSE" | jq -r '.token' | head -c 20)..."
else
  echo "❌ Login failed"
  echo "   Error: $(echo "$LOGIN_RESPONSE" | jq -r '.error')"
fi

rm -f $COOKIE_JAR
