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

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

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

  /**
   * Project deleted
   */
  const deleted = async (payload: FrontendPayload<AnyProject>) => {
    fastify.eventbus.emit("broadcastProjectDeleted", payload)
    fastify.log.info(
      `[eventbus] project broadcast deleted ${payload.body.item._id}`,
    )
  }

  /**
   * Register event handlers
   */
  fastify.eventbus.on("coreProjectCreated", created)
  fastify.eventbus.on("coreProjectUpdated", updated)
  fastify.eventbus.on("coreProjectDeleted", deleted)
}

export default registerEvents
