import { defineRouter } from "#q-app/wrappers";
import {
  createRouter,
  createMemoryHistory,
  createWebHistory,
  createWebHashHistory,
} from "vue-router";
import routes from "./routes";
import { Notify } from "quasar";
import { permissionStore } from "src/stores/permission";
import { i18n } from "src/boot/i18n";
import { userStore } from "src/stores/user";
import { useAuth } from "src/composables/useAuth";

const AUTH_ROUTES = ["LoginPage", "ForgotPasswordPage", "VerifyEmailPage", "VerifyCodePage", "ResetPasswordPage"];

const HOME_BY_TIPO = {
  administrador: "DashboardPage",
  associado:     "CarteirinhaPage",
  parceiro:      "ValidarCarteirinhaPage",
};

export default defineRouter(function () {
  const createHistory = process.env.SERVER
    ? createMemoryHistory
    : process.env.VUE_ROUTER_MODE === "history"
      ? createWebHistory
      : createWebHashHistory;

  const Router = createRouter({
    scrollBehavior: () => ({ left: 0, top: 0 }),
    routes,
    history: createHistory(process.env.VUE_ROUTER_BASE),
  });

  let refreshed = false;

  Router.beforeEach(async (to, from, next) => {
    const store = userStore();

    if (store.accessToken == null && !refreshed) {
      try {
        await useAuth().refresh();
      } catch {
        refreshed = true;
        if (!AUTH_ROUTES.includes(to.name)) {
          return next({ name: "LoginPage" });
        }
        return next();
      }
    }

    if (store.accessToken && AUTH_ROUTES.includes(to.name)) {
      const home = HOME_BY_TIPO[store.userTipo] ?? "HomePage";
      return next({ name: home });
    }

    if (to.meta.requireAuth && !store.accessToken) {
      return next({ name: "LoginPage" });
    }

    if (to.meta.requiredPermission) {
      const { getAccess } = permissionStore();
      if (!getAccess(to.meta.requiredPermission, "view")) {
        Notify.create({
          message: i18n.global.t("validation.permissions.view"),
          type: "negative",
        });
        return next(from);
      }
    }

    if (to.meta.allowedTypes?.length && store.userTipo) {
      if (!to.meta.allowedTypes.includes(store.userTipo)) {
        Notify.create({
          message: i18n.global.t("validation.permissions.view"),
          type: "negative",
        });
        return next({ name: "HomePage" });
      }
    }

    return next();
  });

  return Router;
});
