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

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

  const handler = async (req: FastifyRequest, reply: FastifyReply) => {
    try {
      const payload = await tagService.readTags(
        fastify,
        req.requestParams,
        req.query,
      )

      if (!payload || payload.length === 0) {
        return reply.code(204).send()
      }

      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 all tags for the given project.",
      tags: ["core/tag"],
      params: {},
    },
  }
}
