import type { CompositionBody } from "../composition.service"
import type { Static } from "@sinclair/typebox"
import type { FastifyReply, FastifyRequest } from "fastify"
import type { PluginFastifyInstance } from "types"
import { Type } from "@sinclair/typebox"
import { compositionUpdateSchema } from "../composition.schema"

const permissions = ["user.isAdmin"]

const ParamsSchema = Type.Object({
  _id: Type.String(),
})

type Params = Static<typeof ParamsSchema>

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

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

      const payload = await compositionService.updateComposition(
        fastify,
        req.requestParams,
        _id,
        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: "dataUpdate",
      broadcastChannels: ["compositionUpdated"],
    },
    schema: {
      summary: "Update a composition",
      tags: ["core/composition"],

      params: ParamsSchema,
      body: compositionUpdateSchema,
    },
  }
}
