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";
import { Capacitor } from "@capacitor/core";
import { App as CapacitorApp } from "@capacitor/app";
/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Router instance.
 */

// Telas acessíveis sem autenticação (login, recuperação de senha e primeiro acesso).
const PUBLIC_ROUTES = [
  "LoginPage",
  "ForgotPasswordPage",
  "VerifyEmailPage",
  "VerifyCodePage",
  "ResetPasswordPage",
  "FirstAccessPage",
  "FirstAccessFormPage",
];

export default defineRouter(function (/* { store, ssrContext } */) {
  const createHistory = process.env.SERVER
    ? createMemoryHistory
    : process.env.VUE_ROUTER_MODE === "history"
      ? createWebHistory
      : createWebHashHistory;

  const Router = createRouter({
    scrollBehavior: () => ({ left: 0, top: 0 }),
    routes,

    // Leave this as is and make changes in quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    history: createHistory(process.env.VUE_ROUTER_BASE),
  });
  let refreshed = false;
  Router.beforeEach(async (to, from, next) => {
    if (userStore().accessToken == null && !refreshed) {
      try {
        await useAuth().refresh();
      } catch {
        refreshed = true;
        if (!PUBLIC_ROUTES.includes(to.name)) {
          return next({ name: "LoginPage" });
        }
        return next();
      }
    }
    if (userStore().accessToken) {
      if (PUBLIC_ROUTES.includes(to.name)) {
        return next({ name: "CarteirinhaPage" });
      }
    }
    if (to.meta.requiredPermission) {
      const { getAccess } = permissionStore();
      const permission = getAccess(to.meta.requiredPermission, "view");
      if (!permission) {
        Notify.create({
          message: i18n.global.t("validation.permissions.view"),
          type: "negative",
        });
        return next(from);
      }
    }
    return next();
  });

  if (Capacitor.isNativePlatform()) {
    CapacitorApp.addListener("backButton", ({ canGoBack }) => {
      if (!canGoBack) {
        CapacitorApp.exitApp();
      } else {
        Router.go(-1);
      }
    });
  }

  return Router;
});
