import { createRouter, createWebHistory } from "vue-router";
import LedgerView from "./views/LedgerView.vue";
import { useAuthStore } from "./stores/auth";

export const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      name: "ledger",
      component: LedgerView,
    },
    {
      path: "/invite",
      name: "invite",
      component: () => import("./views/InviteView.vue"),
      meta: { public: true },
    },
    {
      path: "/login",
      name: "login",
      component: () => import("./views/LoginView.vue"),
      meta: { public: true },
    },
    {
      path: "/join-ledger",
      name: "join-ledger",
      component: () => import("./views/JoinLedgerView.vue"),
      meta: { public: true },
    },
    {
      path: "/prototype/entry-detail",
      name: "entry-detail-prototype",
      component: () => import("./views/EntryDetailPrototypeView.vue"),
    },
    {
      path: "/entries/:id",
      name: "entry-detail",
      component: () => import("./views/EntryDetailView.vue"),
    },
    {
      path: "/stats",
      name: "stats",
      component: () => import("./views/StatsView.vue"),
    },
    {
      path: "/query",
      name: "query",
      component: () => import("./views/StatsEntriesView.vue"),
    },
    {
      path: "/ledgers",
      name: "ledgers",
      component: () => import("./views/LedgersView.vue"),
    },
    {
      path: "/ledger/settings",
      name: "ledger-settings",
      component: () => import("./views/LedgerSettingsView.vue"),
    },
    {
      path: "/me",
      name: "me",
      component: () => import("./views/MeView.vue"),
    },
  ],
});

router.beforeEach(async (to) => {
  const auth = useAuthStore();
  await auth.loadSession();
  if (to.meta.public) {
    if (to.name === "login" && auth.user) return { name: "ledger" };
    return true;
  }
  if (!auth.user) return { name: "login", query: { redirect: to.fullPath } };
  return true;
});
