import type { InteractionLinkBody } from "../interactionLink.service"
import type { FastifyReply, FastifyRequest } from "fastify"
import type { 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 {
      // Validate that body is an array
      if (!Array.isArray(req.body)) {
        return reply.badRequest(
          "Request body must be an array of interactionLinks",
        )
      }

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

      const payload = await interactionLinkService.createInteractionLinks(
        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: ["interactionLinksCreated"],
    },
    schema: {
      summary: "Create multiple interactionLinks in bulk",
      tags: ["core/interactionLink"],
      body: {
        type: "array",
        items: interactionLinkCreateSchema,
        minItems: 1,
      },
    },
  }
}
