import type { TagBody } from "../tag.service"
import type { FastifyReply, FastifyRequest } from "fastify"
import type { PluginFastifyInstance } from "types"
import { tagCreateSchema } from "../tag.schema"

const permissions = ["user.isAdmin"]

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

  const handler = async (
    req: FastifyRequest<{
      Body: TagBody[]
    }>,
    reply: FastifyReply,
  ) => {
    try {
      // Validate that body is an array
      if (!Array.isArray(req.body)) {
        return reply.badRequest("Request body must be an array of tags")
      }

      // Validate that array is not empty
      if (req.body.length === 0) {
        return reply.badRequest("Request body cannot be an empty array")
      }

      const payload = await tagService.createTags(
        fastify,
        req.requestParams,
        req.body,
        req.user._id,
      )

      return payload
    } 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: ["tagsCreated"],
    },
    schema: {
      summary: "Create multiple tags in bulk",
      tags: ["core/tag"],
      body: {
        type: "array",
        items: tagCreateSchema,
        minItems: 1,
      },
    },
  }
}
