import { type FastifyInstance } from "fastify"
import { type AnyAccount } from "../account.schema"
import { type FrontendPayload } from "@c/payload/payloadTypes"

const registerEvents = (fastify: FastifyInstance) => {
  /**
   * Account created
   */
  const created = (payload: FrontendPayload<AnyAccount>) => {
    fastify.eventbus.emit("broadcastDataUpdated", payload)
    fastify.eventbus.emit("broadcastAccountCreated", payload)
    fastify.log.info(
      `[eventbus] account broadcast created ${payload.appSessionId}`,
    )
  }

  /**
   * Account updated
   */
  const updated = (payload: FrontendPayload<AnyAccount>) => {
    fastify.eventbus.emit("broadcastDataUpdated", payload)
    fastify.log.info(
      `[eventbus] account broadcast updated ${payload.appSessionId}`,
    )
  }

  /**
   * Account deleted
   */
  const deleted = (payload: FrontendPayload<AnyAccount>) => {
    fastify.eventbus.emit("broadcastAccountDeleted", payload)
    fastify.log.info(
      `[eventbus] account broadcast deleted ${payload.appSessionId}`,
    )
  }

  /**
   * Register event handlers
   */
  fastify.eventbus.on("coreAccountCreated", created)
  fastify.eventbus.on("coreAccountUpdated", updated)
  fastify.eventbus.on("coreAccountDeleted", deleted)
}

export default registerEvents
