import { $store } from "@racletteCore"
import type { RouteLocationNormalized } from "vue-router"
import { checkForDefaultSlotChange } from "../routeStore"

export default async (
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
) => {
  const { redirect, redirectQuery } = to.query

  // check the url for redirect parameter and navigate to it, if set
  if (redirect && typeof redirect === "string") {
    return {
      path: redirect,
      query: redirectQuery ? JSON.parse(redirectQuery as string) : undefined,
    }
  }

  // show loading animation only, if the default slot's value changes
  if (checkForDefaultSlotChange(to, from)) {
    $store.dispatch({
      type: "ui/update",
      payload: { loading: true },
    })
  }

  return true
}
