import type { MiddlewareHandler } from 'hono'
import { getAppOrigins } from '../lib/origins'

/**
 * CORS middleware — credentialed, origin-pinned.
 * Never uses wildcard origin (*).
 */
export const corsMiddleware: MiddlewareHandler = async (c, next) => {
  const origin = c.req.header('Origin')
  const allowedOrigins = getAppOrigins({
    environment: (c.env as { ENVIRONMENT?: string } | undefined)?.ENVIRONMENT,
  })
  const allowedOrigin = origin && allowedOrigins.has(origin) ? origin : undefined
  const setCorsHeaders = () => {
    if (!allowedOrigin) return
    c.header('Access-Control-Allow-Origin', allowedOrigin)
    c.header('Access-Control-Allow-Credentials', 'true')
    c.header('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS')
    c.header(
      'Access-Control-Allow-Headers',
      'Content-Type, Authorization, X-Requested-With'
    )
    c.header('Vary', 'Origin')
  }

  // Handle preflight
  if (c.req.method === 'OPTIONS') {
    setCorsHeaders()
    return c.newResponse('', { status: 204 })
  }

  await next()

  setCorsHeaders()
}
