import type { AnyComposition } from "../composition.schema"
import type { FrontendPayload } from "@c/payload/payloadTypes"
import type { PluginFastifyInstance } from "types"

export const registerEvents = (fastify: PluginFastifyInstance) => {
  /*
   * composition created and created
   */
  const created = async (payload: FrontendPayload<AnyComposition>) => {
    fastify.eventbus.emit("broadcastCompositionCreated", payload)
    fastify.log.info(
      `[eventbus] composition broadcast created ${payload.body.items}`,
    )
  }

  /*
   * composition deleted
   */
  const deleted = async (payload: FrontendPayload<AnyComposition>) => {
    fastify.eventbus.emit("broadcastCompositionDeleted", payload)
    fastify.log.info(
      `[eventbus] composition broadcast deleted ${payload.body.items}`,
    )
  }

  /**
   * Register those functions for eventbus events
   */
  fastify.eventbus.on("coreCompositionCreated", created)
  fastify.eventbus.on("coreCompositionDeleted", deleted)
}

export default registerEvents
