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 {
      const payload = await compositionService.createComposition(
        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: ["compositionCreated"],
    },
    schema: {
      summary: "Create a new composition",
      tags: ["core/composition"],
      body: compositionCreateSchema,
    },
  }
}
