export default defineEventHandler((event) => {
  const origin = getHeader(event, 'origin')
  const path = event.path || ''

  // Rutas públicas que siempre permiten CORS desde cualquier origen
  const publicRoutes = ['/manifest.webmanifest', '/sw.js', '/workbox-', '/_nuxt/', '/icons/', '/screenshots/']
  const isPublicRoute = publicRoutes.some(route => path.startsWith(route))

  if (isPublicRoute) {
    setHeaders(event, {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
      'Access-Control-Max-Age': '86400'
    })
  } else if (origin && (origin.endsWith('.nucleoriofrio.com') || origin === 'https://nucleoriofrio.com')) {
    // Permitir CORS desde cualquier subdominio de .nucleoriofrio.com para otras rutas
    setHeaders(event, {
      'Access-Control-Allow-Origin': origin,
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With',
      'Access-Control-Allow-Credentials': 'true',
      'Access-Control-Max-Age': '86400'
    })
  }

  // Manejar preflight requests
  if (getMethod(event) === 'OPTIONS') {
    event.node.res.statusCode = 204
    event.node.res.end()
  }
})
