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

const permissions = ["user.isAdmin"]

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

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

  const handler = async (
    req: FastifyRequest<{
      Params: Params
      Body: TagBody
    }>,
    reply: FastifyReply,
  ) => {
    try {
      const { _id } = req.params

      const payloadWithTag = await tagService.updateTag(
        fastify,
        req.requestParams,
        _id,
        req.body,
        req.user._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: "dataUpdate",
      broadcastChannels: ["tagUpdated"],
    },
    schema: {
      summary: "Update a tag with a provided id",
      description: "Update an existing tag with the given ID",
      tags: ["core/tag"],
      body: tagUpdateSchema,
      params: ParamsSchema,
    },
  }
}
