import type { InteractionLinkBody } from "../interactionLink.service"
import type { FastifyReply, FastifyRequest } from "fastify"
import { PluginFastifyInstance } from "types"
import { interactionLinkCreateSchema } from "../interactionLink.schema"

const permissions = ["user.isAdmin"]

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

  const handler = async (
    req: FastifyRequest<{
      Body: InteractionLinkBody
    }>,
    reply: FastifyReply,
  ) => {
    try {
      const payload = await interactionLinkService.createInteractionLink(
        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: ["interactionLinkCreated"],
    },
    schema: {
      summary: "Create a new interactionLink",
      tags: ["core/interactionLink"],
      body: interactionLinkCreateSchema,
    },
  }
}
