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

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

  /*
   * makes sure child counts between tickets and tags gets updated
   */
  const tagArrayUpdated = async (payload: FrontendPayload<AnyTag>) => {
    fastify.eventbus.emit("broadcastDataUpdated", payload)
    fastify.log.info(`[eventbus] tag broadcast created ${payload.body.items}`)
  }

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

  /**
   * Register those functions for eventbus events
   */
  fastify.eventbus.on("coreTagCreated", created)
  fastify.eventbus.on("coreTagUpdated", updated)
  fastify.eventbus.on("coreTagDeleted", deleted)
  fastify.eventbus.on("coreTagArrayUpdated", tagArrayUpdated)
}

export default registerEvents
