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

const permissions = ["user.isAdmin"]

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

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

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

      const payloadWithTag = await tagService.createTag(
        fastify,
        req.requestParams,
        { ...req.body, project, owner: 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: "dataCreate",
      broadcastChannels: ["tagCreated"],
    },
    schema: {
      summary: "Create a new Tag with a given project.",
      description: "Create a new Tag given a project",
      tags: ["core/tag"],
      body: tagCreateSchema,
      params: ParamsSchema,
    },
  }
}
