import type { Router } from "vue-router"
import type EventEmitter from "@racletteCore/lib/eventEmitter"
import { applyCompositionSlotsFromRoute } from "./routeStore"

/**
 * Wire router reactions to the global event bus.
 * Kept separate from router creation so it can be invoked from initApp (testable).
 */
export const registerRouterEventHandlers = (
  router: Router,
  eventbus: EventEmitter,
) => {
  eventbus.on("ui/syncRouteCompositions", () => {
    applyCompositionSlotsFromRoute(router.currentRoute.value)
  })

  eventbus.on("backend/error", (error) => {
    if (error.name === "AxiosError") {
      const errorResponse = error.response?.data
      if (errorResponse?.code === "FST_JWT_AUTHORIZATION_TOKEN_EXPIRED") {
        const currentUrl = router.currentRoute.value.fullPath
        if (window.location.href !== window.location.origin + "/login") {
          window.location.href =
            window.location.origin + "/login?redirect=" + currentUrl
        }
      }
    }
  })
}
