import type { FastifyInstance, RouteOptions, FastifySchema } from "fastify"
import fastifyPlugin from "fastify-plugin"
import { CommonHeadersSchema } from "../validation/sharedSchemas"

// Properly type the schema object
type ExtendedSchema = FastifySchema & {
  headers?: Record<string, unknown>
}

export default fastifyPlugin(async (fastify: FastifyInstance) => {
  // Add shared schemas
  fastify.addSchema({
    $id: "commonHeaders",
    ...CommonHeadersSchema,
  })

  // Add hook to validate headers for all routes
  fastify.addHook("onRoute", (routeOptions: RouteOptions) => {
    // Skip if route explicitly opts out of header validation
    if (routeOptions.skipHeaderValidation) return

    // Merge existing schema with common headers
    const routeSchema = (routeOptions.schema || {}) as ExtendedSchema
    routeSchema.headers = {
      ...(routeSchema.headers || {}),
      ...CommonHeadersSchema.properties, // Use .properties to get the actual schema object
    }
    routeOptions.schema = routeSchema
  })
})
