import { getPreRegistration } from '../../../utils/webauthn-challenges.js'
import { generateRegistrationOptions } from '@simplewebauthn/server'
import { getWebAuthnConfig } from '../../../utils/webauthn-config.js'

export default defineEventHandler(async (event) => {
  const registrationId = getRouterParam(event, 'registrationId')
  const requestOrigin = getHeader(event, 'origin')
  const userAgent = getHeader(event, 'user-agent')
  
  console.log('[DEBUG] ===== GET register-passkey-options/[registrationId] =====')
  console.log('[DEBUG] Request Details:', {
    registrationId,
    origin: requestOrigin,
    userAgent: userAgent?.substring(0, 100),
    timestamp: new Date().toISOString(),
    method: getMethod(event),
    note: 'Dieser Endpoint wird vom Smartphone aufgerufen, um die Options für Cross-Device zu erhalten'
  })

  if (!registrationId) {
    throw createError({ statusCode: 400, message: 'registrationId ist erforderlich' })
  }

  // Hole Pre-Registration-Daten
  const pre = getPreRegistration(registrationId)
  if (!pre) {
    console.error('[DEBUG] Pre-registration not found', { registrationId })
    throw createError({ statusCode: 404, message: 'Registrierungs-Session nicht gefunden oder abgelaufen' })
  }

  const { challenge, userId, name, email } = pre
  console.log('[DEBUG] Pre-registration found', {
    userId,
    email: email?.substring(0, 10) + '...',
    hasChallenge: !!challenge
  })

  const { rpId, rpName, origin: webauthnOrigin } = getWebAuthnConfig()

  // Generiere Options neu (mit der gespeicherten Challenge)
  const options = await generateRegistrationOptions({
    rpName,
    rpID: rpId,
    userID: new TextEncoder().encode(String(userId)),
    userName: email,
    userDisplayName: name,
    attestationType: 'none',
    authenticatorSelection: {
      residentKey: 'preferred',
      userVerification: 'preferred'
    },
    timeout: 300000,
    challenge: challenge // Verwende die gespeicherte Challenge
  })

  console.log('[DEBUG] Options regenerated for Cross-Device', {
    hasChallenge: !!options.challenge,
    challengeMatches: options.challenge === challenge,
    rpId: options.rp?.id
  })

  // CORS-Header für Cross-Device
  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, OPTIONS')
    setHeader(event, 'Access-Control-Allow-Headers', 'Content-Type, Authorization, Origin, X-Requested-With')
  }

  return {
    success: true,
    registrationId,
    options
  }
})
