import type { Request, Response, NextFunction } from 'express'
import type { RuntimeConfig } from '../types/runtime-config.js'

export function createCorsMiddleware(
  config: RuntimeConfig,
): (req: Request, res: Response, next: NextFunction) => void {
  const allowedOrigins = config.cors.allowedOrigins
  const isWildcard = allowedOrigins.length === 1 && allowedOrigins[0] === '*'

  return function corsMiddleware(req: Request, res: Response, next: NextFunction): void {
    if (isWildcard) {
      res.setHeader('Access-Control-Allow-Origin', '*')
    } else {
      res.setHeader('Vary', 'Origin')
      const origin = req.headers.origin
      if (origin && allowedOrigins.includes(origin)) {
        res.setHeader('Access-Control-Allow-Origin', origin)
        res.setHeader('Access-Control-Allow-Credentials', 'true')
      }
    }

    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization')
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
    res.setHeader('Access-Control-Max-Age', '86400')

    if (req.method === 'OPTIONS') {
      res.sendStatus(204)
      return
    }

    next()
  }
}
