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

const permissions = ["user.isAdmin"]

const ParamsSchema = Type.Object({
  _id: 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 { _id } = req.params

      const payloadWithTag = await tagService.hardDeleteTag(
        fastify,
        req.requestParams,
        _id,
      )

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

  return {
    handler,
    onRequest: [fastify.authenticate, fastify.checkPermissions(permissions)],
    config: {
      type: "dataHardDeleted",
      broadcastChannels: ["tagHardDeleted"],
    },
    schema: {
      summary: "Permanently delete a tag by id",
      description:
        "Hard delete a tag if it has been previously disabled and there are no tickets assigned to it",
      tags: ["core/tag"],
      params: ParamsSchema,
    },
  }
}
