#!/bin/bash
echo "🐳 Testing Authentication in Docker Environment..."
echo ""

# 1. Health check
echo "1️⃣ Checking application health..."
HEALTH=$(curl -s http://localhost:9000/api/health | jq -r .status)
if [ "$HEALTH" = "healthy" ]; then
  echo "   ✅ Application healthy"
else
  echo "   ❌ Application not healthy"
  exit 1
fi
echo ""

# 2. CSRF token
echo "2️⃣ Testing CSRF token generation..."
CSRF_TOKEN=$(curl -s -c /tmp/docker-cookies.txt http://localhost:9000/api/auth/csrf | jq -r .csrfToken)
if [ -n "$CSRF_TOKEN" ] && [ "$CSRF_TOKEN" != "null" ]; then
  echo "   ✅ CSRF token: ${CSRF_TOKEN:0:20}..."
else
  echo "   ❌ Failed to get CSRF token"
  exit 1
fi
echo ""

# 3. Test login API
echo "3️⃣ Testing login API..."
LOGIN_RESPONSE=$(curl -s -b /tmp/docker-cookies.txt -c /tmp/docker-cookies.txt \
  -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": "Mw!d1Str0ng#P@ss2025"}')

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')"
else
  echo "   ❌ Login failed"
  echo "   Error: $(echo "$LOGIN_RESPONSE" | jq -r '.error')"
  echo "   Response: $LOGIN_RESPONSE" | jq
fi
echo ""

# 4. Test dashboard access check
echo "4️⃣ Testing dashboard access..."
DASHBOARD_CHECK=$(curl -s http://localhost:9000/api/dashboard/access | jq)
echo "$DASHBOARD_CHECK"
echo ""

# 5. Test forgot password (CSRF not required)
echo "5️⃣ Testing forgot password API (without CSRF)..."
FORGOT_RESPONSE=$(curl -s -X POST http://localhost:9000/api/auth/forgot-password \
  -H "Content-Type: application/json" \
  -d '{"identifier": "realtest@mawidi.com"}')

if echo "$FORGOT_RESPONSE" | jq -e '.success' > /dev/null 2>&1; then
  echo "   ✅ Forgot password works (no CSRF required)"
  echo "   Method: $(echo "$FORGOT_RESPONSE" | jq -r '.method')"
  if echo "$FORGOT_RESPONSE" | jq -e '.code' > /dev/null 2>&1; then
    echo "   OTP (dev mode): $(echo "$FORGOT_RESPONSE" | jq -r '.code')"
  fi
else
  echo "   ❌ Forgot password failed"
  echo "   Error: $(echo "$FORGOT_RESPONSE" | jq -r '.error')"
fi
echo ""

echo "🎉 Docker environment authentication test complete!"
rm -f /tmp/docker-cookies.txt
