import type { InteractionLinkBody } from "../interactionLink.service"
import type { Static } from "@sinclair/typebox"
import type { FastifyReply, FastifyRequest } from "fastify"
import { PluginFastifyInstance } from "types"
import { Type } from "@sinclair/typebox"
import { interactionLinkUpdateSchema } from "../interactionLink.schema"

const permissions = ["user.isAdmin"]

const ParamsSchema = Type.Object({
  _id: Type.String(),
})
type Params = Static<typeof ParamsSchema>

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

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

      const payload = await interactionLinkService.updateInteractionLink(
        fastify,
        req.requestParams,
        _id,
        req.body,
      )

      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: ["interactionLinkUpdated"],
    },
    schema: {
      summary: "Update a interactionLink",
      tags: ["core/interactionLink"],

      params: ParamsSchema,
      body: interactionLinkUpdateSchema,
    },
  }
}
