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

const registerEvents = (fastify: PluginFastifyInstance) => {
  /**
   * WorkSession created
   */
  const created = async (payload: FrontendPayload<AnyWorkSession>) => {
    fastify.eventbus.emit("broadcastDataUpdated", payload)
    fastify.eventbus.emit("broadcastWorkSessionCreated", payload)
    fastify.log.info(
      `[eventbus] workSession broadcast created ${payload.body.item._id}`,
    )
  }

  /**
   * WorkSession updated
   */
  const updated = async (payload: FrontendPayload<AnyWorkSession>) => {
    fastify.eventbus.emit("broadcastDataUpdated", payload)
    fastify.log.info(
      `[eventbus] workSession broadcast updated ${payload.body.item._id}`,
    )
  }

  /**
   * WorkSession deleted
   */
  const deleted = async (payload: FrontendPayload<AnyWorkSession>) => {
    fastify.eventbus.emit("broadcastWorkSessionDeleted", payload)
    fastify.log.info(
      `[eventbus] workSession broadcast deleted ${payload.body.item._id}`,
    )
  }

  /**
   * Register event handlers
   */
  fastify.eventbus.on("coreWorkSessionCreated", created)
  fastify.eventbus.on("coreWorkSessionUpdated", updated)
  fastify.eventbus.on("coreWorkSessionDeleted", deleted)
}

export default registerEvents
