import type { CompositionBody } from "../composition.service"
import type { FastifyReply, FastifyRequest } from "fastify"
import type { PluginFastifyInstance } from "types"
import { compositionCreateSchema } from "../composition.schema"

const permissions = ["user.isAdmin"]

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

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

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

      const payload = await compositionService.createCompositions(
        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: ["compositionsCreated"],
    },
    schema: {
      summary: "Create multiple compositions in bulk",
      tags: ["core/composition"],
      body: {
        type: "array",
        items: compositionCreateSchema,
        minItems: 1,
      },
    },
  }
}
