#!/bin/bash

# CORS 403 Hızlı Çözüm Script
# Production origin'i DATABASE WHITELIST'e ekler
#
# Sistem Database-Driven CORS kullanıyor:
# 1. PostgreSQL'de cors_whitelists ve cors_blacklists tabloları
# 2. Redis cache (1 saat TTL)
# 3. Dynamic CORS middleware runtime'da database'den okuyor

echo "🔧 CORS 403 Hızlı Çözüm (Database-Driven)"
echo "=========================================="

# Değişkenler
BACKEND_URL="${BACKEND_URL:-https://goauth.beyhano.net.tr}"
FRONTEND_ORIGIN="${FRONTEND_ORIGIN:-https://nextgo.beyhano.net.tr}"
ADMIN_EMAIL="${ADMIN_EMAIL:-admin@gauth.local}"
ADMIN_PASSWORD="${ADMIN_PASSWORD:-Admin@123}"

echo "Backend URL: $BACKEND_URL"
echo "Frontend Origin: $FRONTEND_ORIGIN"

# 1. Admin Login
echo -e "\n📝 Step 1: Admin Login..."
LOGIN_RESPONSE=$(curl -s -X POST $BACKEND_URL/v1/auth/login \
  -H "Content-Type: application/json" \
  -d "{
    \"email\":\"$ADMIN_EMAIL\",
    \"password\":\"$ADMIN_PASSWORD\"
  }")

TOKEN=$(echo $LOGIN_RESPONSE | jq -r '.access_token')

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

echo "✅ Login successful"
echo "Token: ${TOKEN:0:30}..."

# 2. Check if origin already in whitelist
echo -e "\n📝 Step 2: Checking existing whitelist..."
WHITELIST_RESPONSE=$(curl -s -X GET $BACKEND_URL/v1/settings/cors/whitelist \
  -H "Authorization: Bearer $TOKEN")

EXISTING=$(echo $WHITELIST_RESPONSE | jq -r ".[] | select(.origin==\"$FRONTEND_ORIGIN\") | .id")

if [ ! -z "$EXISTING" ] && [ "$EXISTING" != "null" ]; then
  echo "✅ Origin already in whitelist (ID: $EXISTING)"
  echo "Checking if active..."

  IS_ACTIVE=$(echo $WHITELIST_RESPONSE | jq -r ".[] | select(.id==\"$EXISTING\") | .is_active")

  if [ "$IS_ACTIVE" = "false" ]; then
    echo "⚠️  Origin exists but is inactive. Activating..."
    UPDATE_RESPONSE=$(curl -s -X PUT "$BACKEND_URL/v1/settings/cors/whitelist/$EXISTING" \
      -H "Authorization: Bearer $TOKEN" \
      -H "Content-Type: application/json" \
      -d '{"is_active": true}')
    echo "✅ Activated: $UPDATE_RESPONSE"
  else
    echo "✅ Origin is active"
  fi
else
  # 3. Add origin to whitelist
  echo -e "\n📝 Step 3: Adding origin to whitelist..."
  CREATE_RESPONSE=$(curl -s -X POST $BACKEND_URL/v1/settings/cors/whitelist \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d "{
      \"origin\": \"$FRONTEND_ORIGIN\",
      \"description\": \"Production frontend - Auto-added by CORS fix script\"
    }")

  NEW_ID=$(echo $CREATE_RESPONSE | jq -r '.id')

  if [ "$NEW_ID" = "null" ] || [ -z "$NEW_ID" ]; then
    echo "❌ Failed to add origin to whitelist"
    echo "Response: $CREATE_RESPONSE"
    exit 1
  fi

  echo "✅ Origin added to whitelist"
  echo "ID: $NEW_ID"
  echo $CREATE_RESPONSE | jq '{id, origin, is_active, created_at}'
fi

# 4. Add localhost for development (optional)
echo -e "\n📝 Step 4: Adding localhost for development..."
LOCALHOST_ORIGIN="http://localhost:3000"

LOCALHOST_EXISTS=$(echo $WHITELIST_RESPONSE | jq -r ".[] | select(.origin==\"$LOCALHOST_ORIGIN\") | .id")

if [ -z "$LOCALHOST_EXISTS" ] || [ "$LOCALHOST_EXISTS" = "null" ]; then
  LOCALHOST_RESPONSE=$(curl -s -X POST $BACKEND_URL/v1/settings/cors/whitelist \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "origin": "'"$LOCALHOST_ORIGIN"'",
      "description": "Local development"
    }')
  echo "✅ Localhost added: $LOCALHOST_ORIGIN"
else
  echo "✅ Localhost already in whitelist"
fi

# 5. Verify whitelist
echo -e "\n📝 Step 5: Verifying whitelist..."
FINAL_WHITELIST=$(curl -s -X GET $BACKEND_URL/v1/settings/cors/whitelist \
  -H "Authorization: Bearer $TOKEN")

echo "Current whitelist:"
echo $FINAL_WHITELIST | jq '.[] | {origin, is_active, created_at}'

# 6. Test CORS
echo -e "\n📝 Step 6: Testing CORS preflight..."
PREFLIGHT_RESPONSE=$(curl -s -i -X OPTIONS $BACKEND_URL/v1/auth/login \
  -H "Origin: $FRONTEND_ORIGIN" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: content-type")

CORS_HEADER=$(echo "$PREFLIGHT_RESPONSE" | grep -i "Access-Control-Allow-Origin")

if [ ! -z "$CORS_HEADER" ]; then
  echo "✅ CORS preflight successful!"
  echo "$CORS_HEADER"
else
  echo "⚠️  CORS preflight response:"
  echo "$PREFLIGHT_RESPONSE" | head -20
fi

# Summary
echo -e "\n========================="
echo "✅ CORS Configuration Complete!"
echo "========================="
echo ""
echo "Whitelisted Origins:"
echo $FINAL_WHITELIST | jq -r '.[] | "  - \(.origin) (\(.is_active | if . then "Active" else "Inactive" end))"'
echo ""
echo "Next Steps:"
echo "1. Test from frontend: $FRONTEND_ORIGIN"
echo "2. Check browser console for CORS errors"
echo "3. If still issues, restart backend container"
echo ""
echo "Troubleshooting:"
echo "- View whitelist: curl -X GET $BACKEND_URL/v1/settings/cors/whitelist -H 'Authorization: Bearer \$TOKEN'"
echo "- Clear Redis cache: docker exec -it gauth_redis redis-cli DEL cors:whitelist"
echo "- Restart container: docker restart app_auth_central"
echo ""
echo "Documentation: CORS_403_FIX.md"
