import type { CommonHeadersSchema } from "@c/validation/sharedSchemas"
import type { Static } from "@sinclair/typebox"
import type { FastifyRequest } from "fastify"
import fastifyPlugin from "fastify-plugin"
import { createRequestParams } from "@/utils/request.utils"

type CommonHeaders = Static<typeof CommonHeadersSchema>

const isExcluded = (url: string) => {
  const excludedPaths = ["/health", "/metrics"]
  return excludedPaths.includes(url)
}

export default fastifyPlugin(async (fastify) => {
  fastify.addHook("preHandler", async (request: FastifyRequest) => {
    const routeOptions = request.routeOptions.config
    request.requestParams = createRequestParams(
      request as FastifyRequest<{
        Headers: CommonHeaders
      }>,
      routeOptions || {},
    )
  })
  fastify.addHook("onRequest", (request, reply, done) => {
    done()
  })
  fastify.addHook("onRequest", (request, reply, done) => {
    const url = request.raw.url || ""
    if (!isExcluded(url)) {
      request.log.debug(
        { url: request.raw.url, id: request.id },
        "Received request",
      )
    }

    done()
  })

  fastify.addHook("onResponse", (request, reply, done) => {
    const url = request.raw.url || ""
    if (!isExcluded(url)) {
      request.log.debug(
        {
          url: request.raw.url,
          statusCode: reply.statusCode,
          responseTime: reply.elapsedTime(),
          id: request.id,
        },
        "Request completed",
      )
    }

    done()
  })
})
