import fp from 'fastify-plugin'
import cors from '@fastify/cors'

export const corsPlugin = fp(async (app) => {
  const corsOrigins = process.env.CORS_ORIGINS
  let origin: boolean | string[]

  if (process.env.NODE_ENV === 'development') {
    origin = true // allow all in dev
  } else if (corsOrigins) {
    origin = corsOrigins.split(',').map((o) => o.trim())
  } else {
    origin = false
  }

  await app.register(cors, {
    origin,
    // Allow WebDAV methods for clients that send preflight
    methods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'OPTIONS', 'PROPFIND', 'PROPPATCH', 'MKCOL', 'COPY', 'MOVE', 'LOCK', 'UNLOCK'],
    allowedHeaders: ['Content-Type', 'Authorization', 'Depth', 'Destination', 'Overwrite', 'Lock-Token', 'If', 'X-Location-Id'],
    exposedHeaders: ['DAV', 'Allow', 'Lock-Token', 'ETag'],
    // Don't enforce strict preflight on WebDAV paths (clients don't send Origin)
    strictPreflight: false,
  })
})
