import { requestIdContext } from '@/context'
import { type LoaderFunctionArgs } from 'react-router'

export const loggingMiddleware = async (
  { request, context }: LoaderFunctionArgs,
  next
) => {
  const requestId = crypto.randomUUID()
  context.set(requestIdContext, requestId)

  console.log(
    `[${new Date().toISOString()}] [${requestId}] ${request.method} ${request.url}`
  )

  const start = performance.now()
  const response = await next()
  const duration = performance.now() - start

  console.log(
    `[${new Date().toISOString()}] [${requestId}] Response ${response.status} (${duration}ms)`
  )

  response.headers.set('Server-Timing', `page;req=${requestId};dur=${duration}`)

  return response
}
