const BACKEND = process.env.BACKEND_URL || 'http://localhost:8080'

async function proxy(request, { params }) {
  const path = (await params).path.join('/')
  const { search } = new URL(request.url)
  const url = `${BACKEND}/api/${path}${search}`

  const headers = new Headers(request.headers)
  headers.delete('host')
  headers.delete('origin')

  const init = { method: request.method, headers }
  if (!['GET', 'HEAD'].includes(request.method)) {
    init.body = request.body
    init.duplex = 'half'
  }

  const res = await fetch(url, init)
  return new Response(res.body, {
    status: res.status,
    statusText: res.statusText,
    headers: res.headers,
  })
}

export { proxy as GET, proxy as POST, proxy as PUT, proxy as DELETE, proxy as PATCH }
