import type { FastifyReply, FastifyRequest } from "fastify"
import { PluginFastifyInstance } from "types"
import { Type, type Static } from "@sinclair/typebox"
import { ForbiddenError } from "@/utils/errors"

const ParamsSchema = Type.Object({
  _id: Type.Optional(Type.String()),
})
type Params = Static<typeof ParamsSchema>

export default (fastify: PluginFastifyInstance) => {
  const tagService = fastify.custom.tagService

  const handler = async (
    req: FastifyRequest<{ Params: Params }>,
    reply: FastifyReply,
  ) => {
    try {
      const payload = await tagService.readTags(fastify, req.requestParams, {
        id: req.params._id,
      })

      return reply.send(payload)
    } catch (error: any) {
      fastify.log.error(error)
      return reply.internalServerError(error.message)
    }
  }

  return {
    handler,
    onRequest: [fastify.authenticate],
    config: {
      type: "dataRead",
    },
    schema: {
      summary: "Get a tag by id.",
      tags: ["core/tag"],
      params: ParamsSchema,
    },
  }
}
