import AppLayout from "../layout/AppLayout.vue";
import AuthLayout from "../layout/AuthLayout.vue";
import { hydrateUser, userRef } from "../composables/useAuth";
import { useNavigation } from "../composables/useNavigation";
import { normalizePermissionList } from "../utils/permissionList";

import { createRouter, createWebHistory } from "vue-router";

export const coreRoutes = [
  {
    path: "/auth",
    component: AuthLayout,
    children: [
      {
        path: "login",
        name: "login",
        meta: { guest: true },
        component: () => import("../views/auth/LoginView.vue"),
      },
      {
        path: "oops",
        name: "auth-oops",
        component: () => import("../views/pages/Oops.vue"),
      },
      {
        path: "access",
        name: "auth-access",
        component: () => import("../views/pages/AccessDenied.vue"),
      },
    ],
  },
  {
    path: "/pages/notfound",
    component: AuthLayout,
    children: [
      {
        path: "",
        name: "pages-not-found",
        component: () => import("../views/pages/NotFound.vue"),
      },
    ],
  },
  {
    path: "/offers/public/:uuid",
    name: "offers-public-view",
    meta: {
      title: "Offerte",
    },
    component: () =>
      import("../modules/offers/views/PublicOfferView.vue"),
  },
  {
    path: "/",
    name: "authenticated",
    component: AppLayout,
    meta: { requiresAuth: true },
    children: [
      {
        path: "",
        name: "authenticated-redirect-dashboard",
        redirect: "/dashboard",
      },
      {
        path: "dashboard",
        name: "dashboard",
        meta: {
          breadcrumb: ["Dashboard"],
          title: "Dashboard",
        },
        component: () => import("../views/dashboard/EcommerceView.vue"),
      },
      {
        path: "settings",
        name: "settings",
        meta: {
          breadcrumb: ["Instellingen"],
          title: "Instellingen",
        },
        component: () => import("../views/settings/SettingsRedirectView.vue"),
      },
      {
        path: "settings/organization",
        name: "settings-organization",
        meta: {
          breadcrumb: ["Instellingen", "Organisatie"],
          title: "Organisatie",
          permission: "settings.organization.view",
        },
        component: () => import("../views/organization/OrganizationProfileView.vue"),
      },
      {
        path: "settings/users",
        name: "settings-users",
        meta: {
          breadcrumb: ["Instellingen", "Gebruikers"],
          title: "Gebruikers",
          permission: "users.view",
        },
        component: () => import("../views/settings/UsersView.vue"),
      },
      {
        path: "settings/roles",
        name: "settings-roles",
        meta: {
          breadcrumb: ["Instellingen", "Rollen"],
          title: "Rollen",
          permission: "roles.view",
        },
        component: () => import("../views/settings/RolesManagementView.vue"),
      },
      {
        path: "settings/activity-log",
        name: "settings-activity-log",
        meta: {
          breadcrumb: ["Instellingen", "Activiteitenlogboek"],
          title: "Activiteitenlogboek",
          permission: "activitylog.view",
        },
        component: () => import("../views/settings/ActivityLogView.vue"),
      },
      {
        path: "settings/offers/catalog",
        name: "settings-offers-catalog",
        meta: {
          breadcrumb: ["Instellingen", "Offertecatalogus"],
          title: "Offertecatalogus",
          permission: "offers.catalog.manage",
        },
        component: () =>
          import("../modules/offers/views/OfferCatalogSettingsView.vue"),
      },
      {
        path: "settings/offers/templates",
        name: "settings-offers-templates",
        meta: {
          breadcrumb: ["Instellingen", "Offertesjablonen"],
          title: "Offertesjablonen",
          permission: "offers.templates.manage",
        },
        component: () =>
          import("../modules/offers/views/OfferTemplatesSettingsView.vue"),
      },
      {
        path: "settings/invoices/vat-rates",
        name: "settings-invoices-vat",
        meta: {
          module: "invoices",
          breadcrumb: ["Instellingen", "BTW-tarieven"],
          title: "BTW-tarieven",
          permission: "invoices.vat.manage",
        },
        component: () =>
          import("../modules/invoices/views/VatRatesSettingsView.vue"),
      },
      {
        path: "settings/items",
        name: "settings-items-catalog",
        meta: {
          module: "items",
          breadcrumb: ["Instellingen", "Artikelen"],
          title: "Artikelen",
          permission: "items.manage",
        },
        component: () =>
          import("../modules/items/views/ItemsCatalogSettingsView.vue"),
      },
      {
        path: "superadmin",
        component: () => import("../views/superadmin/SuperadminLayout.vue"),
        meta: {
          breadcrumb: ["Superbeheer"],
          title: "Superbeheer",
          permission: "platform.superadmin",
        },
        children: [
          {
            path: "",
            redirect: "/superadmin/modules",
          },
          {
            path: "setup",
            redirect: "/superadmin/installation-health",
          },
          {
            path: "installation-health",
            name: "superadmin-installation-health",
            meta: {
              breadcrumb: ["Superbeheer", "Installatiecontrole"],
              title: "Installatiecontrole",
            },
            component: () =>
              import("../views/superadmin/SuperadminInstallationHealthView.vue"),
          },
          {
            path: "modules",
            name: "superadmin-modules",
            meta: {
              breadcrumb: ["Superbeheer", "Modules"],
              title: "Modules",
            },
            component: () =>
              import("../views/superadmin/SuperadminModulesView.vue"),
          },
          {
            path: "datatable-settings",
            name: "superadmin-datatable-settings",
            meta: {
              breadcrumb: ["Superbeheer", "Tabellen"],
              title: "Tabellen",
            },
            component: () =>
              import("../views/superadmin/SuperadminDataTableSettingsView.vue"),
          },
          {
            path: "navigation",
            name: "superadmin-navigation",
            meta: {
              breadcrumb: ["Superbeheer", "Navigatie"],
              title: "Navigatie",
            },
            component: () =>
              import("../views/superadmin/SuperadminNavigationView.vue"),
          },
          {
            path: "appearance",
            name: "superadmin-appearance",
            meta: {
              breadcrumb: ["Superbeheer", "Thema & lay-out"],
              title: "Thema & lay-out",
            },
            component: () =>
              import("../views/superadmin/MaestroAppearanceSettingsPanel.vue"),
          },
          {
            path: "branding",
            name: "superadmin-branding",
            meta: {
              breadcrumb: ["Superbeheer", "Huisstijl"],
              title: "Huisstijl",
            },
            component: () =>
              import("../views/superadmin/SuperadminBrandingPanel.vue"),
          },
        ],
      },
    ],
  },
  {
    path: "/:pathMatch(.*)*",
    name: "fallback-not-found",
    component: () => import("../views/pages/NotFound.vue"),
  },
];

/**
 * Create the SPA router. Pass an optional callback to register customer routes
 * (e.g. router.addRoute) before the app mounts.
 *
 * @param {(router: import('vue-router').Router) => void} [extendRouter]
 *        Runs after CORE route records are prepared; typically used to {@link Router#addRoute}
 *        more children onto the authenticated layout (`name: authenticated`).
 */
export function createCoreRouter(extendRouter) {
  let bootstrapAuth = false;

  const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: coreRoutes,
  });

  router.beforeEach(async (to, from, next) => {
    if (!bootstrapAuth) {
      await hydrateUser();
      bootstrapAuth = true;
    }

    const isAuthed = Boolean(userRef.value);

    if (to.meta.requiresAuth && !isAuthed) {
      next({
        name: "login",
        query: { redirect: to.fullPath },
        replace: true,
      });

      return;
    }

    if (to.meta.guest && isAuthed) {
      next({ path: "/dashboard", replace: true });

      return;
    }

    const required = to.matched
      .map((r) => r.meta?.permission)
      .filter((p) => typeof p === "string");
    if (required.length && isAuthed && userRef.value) {
      const perms = normalizePermissionList(userRef.value.permissions);
      const allowed = required.every((p) => perms.includes(p));
      if (!allowed) {
        next({ name: "auth-access", replace: true });

        return;
      }
    }

    const moduleSlugs = to.matched
      .map((r) => r.meta?.module)
      .filter((s) => typeof s === "string");
    if (moduleSlugs.length && isAuthed && userRef.value) {
      const enabled = userRef.value.enabled_module_slugs ?? [];
      const moduleOk = moduleSlugs.every((slug) => enabled.includes(slug));
      if (!moduleOk) {
        next({ name: "auth-access", replace: true });

        return;
      }
    }

    if (to.meta.requiresAuth && isAuthed) {
      const { fetchNavigation } = useNavigation();
      await fetchNavigation();
    }

    next();
  });

  if (typeof extendRouter === "function") {
    extendRouter(router);
  }

  return router;
}
