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

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

  /*
   * user updated
   */
  const updated = async (payload: FrontendPayload<AnyUser>) => {
    fastify.eventbus.emit("broadcastDataUpdated", payload)
    fastify.log.info(`[eventbus] user broadcast updated ${payload.body.items}`)
  }

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

  /**
   * Register those functions for eventbus events
   */
  fastify.eventbus.on("coreUserCreated", created)
  fastify.eventbus.on("coreUserUpdated", updated)
  fastify.eventbus.on("coreUserDeleted", deleted)
}

export default registerEvents
