import { getWebAuthnConfig } from '../../utils/webauthn-config.js'

export default defineEventHandler(async (event) => {
  const requestOrigin = getHeader(event, 'origin')
  const { origin: webauthnOrigin } = getWebAuthnConfig()
  
  const userAgent = getHeader(event, 'user-agent')
  const ip = getHeader(event, 'x-forwarded-for') || getHeader(event, 'x-real-ip') || 'unknown'
  
  console.log('[DEBUG] ===== OPTIONS preflight for /api/auth/register-passkey-options =====')
  console.log('[DEBUG] OPTIONS Request Details:', {
    origin: requestOrigin || 'none',
    webauthnOrigin,
    userAgent: userAgent?.substring(0, 100) || 'none',
    ip,
    timestamp: new Date().toISOString(),
    note: 'OPTIONS Preflight für Passkey Registration Options'
  })

  // CORS-Header für Cross-Device Authentication
  const allowedOrigin = requestOrigin || webauthnOrigin
  
  if (allowedOrigin) {
    setHeader(event, 'Access-Control-Allow-Origin', allowedOrigin)
    setHeader(event, 'Access-Control-Allow-Credentials', 'true')
    setHeader(event, 'Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
    setHeader(event, 'Access-Control-Allow-Headers', 'Content-Type, Authorization, Origin, X-Requested-With')
    setHeader(event, 'Access-Control-Max-Age', '86400') // 24 Stunden Cache für Preflight
    console.log('[DEBUG] CORS headers set for OPTIONS', { 
      origin: allowedOrigin,
      requestOrigin,
      webauthnOrigin
    })
  }

  // OPTIONS Preflight-Request: 204 No Content
  setResponseStatus(event, 204)
  return null
})
