/**
 * CORS Middleware
 * Handles Cross-Origin Resource Sharing for API requests
 *
 * Development: Allows all origins for convenience
 * Production: Only allows:
 *   - Explicitly configured origins (via ALLOWED_ORIGINS env var)
 *   - Capacitor app origins (capacitor://, ionic://, http://localhost)
 */

const isDev = process.env.NODE_ENV === 'development'

// Get allowed origins from environment variable
const allowedOriginsEnv = process.env.ALLOWED_ORIGINS || ''
const allowedOrigins = allowedOriginsEnv.split(',').filter(Boolean)

// Capacitor apps use these special origins
const capacitorOrigins = [
  'capacitor://localhost',
  'ionic://localhost',
  'http://localhost', // Android WebView (http)
  'https://localhost' // Android WebView (https)
]

// Combine allowed origins
const prodAllowedOrigins = [...allowedOrigins, ...capacitorOrigins]

export default defineEventHandler((event) => {
  // Only handle API routes
  const path = event.path || event.node.req.url || ''
  if (!path.startsWith('/api/')) {
    return
  }

  // Get the origin from the request
  const origin = getRequestHeader(event, 'origin')

  // In development, allow all origins
  if (isDev) {
    if (origin) {
      setResponseHeader(event, 'Access-Control-Allow-Origin', origin)
      setResponseHeader(event, 'Access-Control-Allow-Credentials', 'true')
    }
    return
  }

  // In production, validate origin
  if (origin) {
    // Check if this is a same-origin request
    // Get the host from the request to determine if origin matches
    const host = getRequestHeader(event, 'host')
    const protocol = getRequestHeader(event, 'x-forwarded-proto') || 'https'
    const requestOrigin = `${protocol}://${host}`

    // Allow same-origin requests (web browser accessing same domain)
    const isSameOrigin = origin === requestOrigin

    // Check if origin is in the allowed list
    const isAllowed = isSameOrigin || prodAllowedOrigins.some((allowed) => {
      // Exact match
      if (allowed === origin) {
        return true
      }
      // For localhost, also allow with port numbers (e.g., http://localhost:3000)
      if (allowed === 'http://localhost' && origin.startsWith('http://localhost')) {
        return true
      }
      if (allowed === 'https://localhost' && origin.startsWith('https://localhost')) {
        return true
      }
      return false
    })

    if (isAllowed) {
      setResponseHeader(event, 'Access-Control-Allow-Origin', origin)
      setResponseHeader(event, 'Access-Control-Allow-Credentials', 'true')
    } else {
      // Log unauthorized CORS attempts in production
      console.warn(`[CORS] Blocked request from unauthorized origin: ${origin}`)
    }
  } else {
    // Some Capacitor apps might not send an Origin header
    // Allow requests without origin header (same-origin or Capacitor)
    // This is safe because browsers always send Origin for cross-origin requests
    setResponseHeader(event, 'Access-Control-Allow-Credentials', 'true')
  }

  // Handle preflight requests
  if (event.node.req.method === 'OPTIONS') {
    setResponseHeader(event, 'Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS')
    setResponseHeader(event, 'Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, Accept, Origin')
    setResponseHeader(event, 'Access-Control-Max-Age', 86400) // 24 hours
    event.node.res.statusCode = 204
    event.node.res.end()
    return
  }
})
