import fp from 'fastify-plugin'
import fastifySwaggerUi from '@fastify/swagger-ui'
import fastifySwagger from '@fastify/swagger'
import yaml from 'js-yaml'
import fs from 'node:fs'

const openapi = yaml.load(fs.readFileSync('./openapi.yaml', 'utf8'))

const config = {
  routePrefix: '/api-docs',
  prefix: process.env.APP_ROOT,
  openapi
}

// This plugin is used to expose the Swagger UI on the /api-docs endpoint
export default fp(async (fastify) => {
  if (process.env.EXPOSE_API_DOCS !== 'true') return

  fastify.log.info('Registering Swagger UI on /api-docs endpoint. To disable this, set EXPOSE_API_DOCS=false.')

  await fastify.register(fastifySwagger, config)

  await fastify.register(fastifySwaggerUi, {
    routePrefix: '/api-docs',
    uiConfig: {
      docExpansion: 'full',
      deepLinking: false
    },
    uiHooks: {
      onRequest: function (request, reply, next) { next() },
      preHandler: function (request, reply, next) { next() }
    },
    staticCSP: true,
    transformStaticCSP: (header) => header,
    transformSpecification: (swaggerObject, request, reply) => { return swaggerObject },
    transformSpecificationClone: true
  })
})