import { createRouter, createWebHashHistory } from "vue-router"
import { fetchCurrentUser, getAuthorizationToken, getLoginPath } from "@/services/auth"

const platform = () => import("@/views/platform/index.vue")
const login = () => import("@/views/login/index.vue")
const chartStyleGuide = () => import("@/views/chartStyleGuide/index.vue")
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      redirect: "/platform",
    },
    {
      path: "/login",
      component: login,
      meta: { public: true },
    },
    {
      path: "/platform",
      component: platform,
    },
    {
      path: "/forest-grass-wet",
      component: platform,
    },
    {
      path: "/chart-style-guide",
      component: chartStyleGuide,
    },

    {
      path: "/:pathMatch(.*)",
      redirect: "/",
    },
  ],
})

let userPromise = null

router.beforeEach(async (to) => {
  if (to.meta.public) {
    if (getAuthorizationToken()) {
      try {
        await ensureCurrentUser()
        return to.query.redirect ? decodeURIComponent(to.query.redirect) : "/platform"
      } catch (error) {
        userPromise = null
      }
    }
    return true
  }

  if (!getAuthorizationToken()) {
    return getLoginPath(to.fullPath)
  }

  try {
    await ensureCurrentUser()
    return true
  } catch (error) {
    userPromise = null
    return getLoginPath(to.fullPath)
  }
})

function ensureCurrentUser() {
  if (!userPromise) {
    userPromise = fetchCurrentUser()
  }
  return userPromise
}

export default router
