import { NextRequest, NextResponse } from 'next/server'
import { writeApiLog } from './logger'

export function loggerWrapper(handler: (req: NextRequest) => Promise<NextResponse>): (req: NextRequest) => Promise<NextResponse> {
  return async function (req: NextRequest) {
    const reqClone = req.clone()

    const response = await handler(req)

    await writeApiLog(
      new NextRequest(req.url, {
        method: req.method,
        headers: req.headers,
        body: reqClone.body ? await reqClone.text() : undefined,
      }),
      response.status,
    )

    return response
  }
}
