/**
 * Globales Request-Logging für Debugging
 * Loggt alle Requests, besonders Passkey-relevante Endpoints
 */

export default defineEventHandler((event) => {
  const url = getRequestURL(event)
  const method = getMethod(event)
  const path = url.pathname
  const origin = getHeader(event, 'origin')
  const userAgent = getHeader(event, 'user-agent')
  const ip = getHeader(event, 'x-forwarded-for') || getHeader(event, 'x-real-ip') || 'unknown'
  
  // Logge nur Passkey-relevante Endpoints (um Logs nicht zu überfluten)
  // Passkey-Endpoints vorläufig deaktiviert
  const passkeyEndpoints = [
    '/api/auth/register-passkey',
    '/api/auth/register-passkey-options',
    '/api/auth/passkeys/registration-options',
    '/api/auth/passkeys/register',
    '/api/auth/passkeys/authentication-options',
    '/api/auth/passkeys/login',
    '/api/auth/passkeys/recovery'
    // '/passkey-register-cross-device' - Seite gelöscht
  ]
  
  // Logge auch alle Requests vom Smartphone (Mobile User-Agent)
  const isMobile = /Mobile|Android|iPhone|iPad/i.test(userAgent || '')
  const isPasskeyEndpoint = passkeyEndpoints.some(ep => path.startsWith(ep)) || (isMobile && path.startsWith('/'))
  
  if (isPasskeyEndpoint) {
    const timestamp = new Date().toISOString()
    
    console.log('')
    console.log('─'.repeat(80))
    console.log(`[REQUEST] ${timestamp} ${method} ${path}`)
    console.log(`[REQUEST] Origin: ${origin || 'none'}`)
    console.log(`[REQUEST] IP: ${ip}`)
    console.log(`[REQUEST] User-Agent: ${userAgent?.substring(0, 150) || 'none'}`)
    console.log(`[REQUEST] Is Mobile: ${isMobile ? '✅ JA' : '❌ NEIN'}`)
    
    // Spezielle Logs für Cross-Device
    if (path.includes('register-passkey') && method === 'POST') {
      console.log(`[REQUEST] 🔑 PASSKEY REGISTRATION REQUEST`)
      if (isMobile) {
        console.log(`[REQUEST] ✅ Request kommt vom Smartphone!`)
      } else {
        console.log(`[REQUEST] ⚠️ Request kommt NICHT vom Smartphone (Desktop-Browser?)`)
      }
    }
    
    if (path.includes('register-passkey') && method === 'OPTIONS') {
      console.log(`[REQUEST] 🔧 OPTIONS Preflight für Passkey Registration`)
      console.log(`[REQUEST] ⚠️ Wenn dieser Request vom Smartphone kommt, sollte der User-Agent Mobile/Android/iPhone enthalten`)
    }
    
    // Logge alle Requests vom Smartphone (für Debugging)
    if (isMobile && path.startsWith('/') && !path.startsWith('/_nuxt') && !path.startsWith('/api')) {
      console.log(`[REQUEST] 📱 SMARTPHONE REQUEST - ${path}`)
      console.log(`[REQUEST] ⚠️ Wenn das Smartphone die Website öffnet, sollten hier Requests erscheinen`)
    }
    
    console.log('─'.repeat(80))
    console.log('')
  }
})
