import { createRouter, createWebHistory } from "vue-router";
import AppLayout from "../views/layout/AppLayout.vue";
import TenantDashboardPage from "../views/modules/TenantDashboardPage.vue";
import ProfilePage from "../views/modules/ProfilePage.vue";
import ProjectPage from "../views/modules/ProjectPage.vue";
import MeetingPage from "../views/modules/MeetingPage.vue";
import AuditPage from "../views/modules/AuditPage.vue";
import FinancePage from "../views/modules/FinancePage.vue";
import UserPage from "../views/modules/UserPage.vue";
import RolePage from "../views/modules/RolePage.vue";
import TenantPage from "../views/modules/TenantPage.vue";
import EnterprisePage from "../views/modules/EnterprisePage.vue";
import MenuPage from "../views/modules/MenuPage.vue";
import PlatformLoginPage from "../views/modules/PlatformLoginPage.vue";
import TenantLoginPage from "../views/modules/TenantLoginPage.vue";
import TenantPasswordSetupPage from "../views/modules/TenantPasswordSetupPage.vue";
import AuditFlowPage from "../views/modules/AuditFlowPage.vue";
import DataPermissionPage from "../views/modules/DataPermissionPage.vue";
import TemplatePage from "../views/modules/TemplatePage.vue";
import TemplateDownloadLogPage from "../views/modules/TemplateDownloadLogPage.vue";
import AuditLogPage from "../views/modules/AuditLogPage.vue";
import ExpertPage from "../views/modules/ExpertPage.vue";
import NotificationPolicyPage from "../views/modules/NotificationPolicyPage.vue";
import NotificationTextTemplatePage from "../views/modules/NotificationTextTemplatePage.vue";
import InAppNotificationPage from "../views/modules/InAppNotificationPage.vue";
import ObservabilityPage from "../views/modules/ObservabilityPage.vue";
import InvoiceProfilePage from "../views/modules/InvoiceProfilePage.vue";
import ExportTaskPage from "../views/modules/ExportTaskPage.vue";
import OperationsDashboardPage from "../views/modules/OperationsDashboardPage.vue";
import PlatformMenuPage from "../views/modules/PlatformMenuPage.vue";
import PlatformUserPage from "../views/modules/PlatformUserPage.vue";
import PlatformRolePage from "../views/modules/PlatformRolePage.vue";
import PlatformDictionaryPage from "../views/modules/PlatformDictionaryPage.vue";
import PlatformSessionPage from "../views/modules/PlatformSessionPage.vue";
import PlatformNotifyGatewayPage from "../views/modules/PlatformNotifyGatewayPage.vue";
import NotFoundPage from "../views/modules/NotFoundPage.vue";
import { refreshAuth } from "../api/modules";
import { pinia } from "../stores";
import { useAuthStore } from "../stores/auth";
import { resolveLoginPath } from "../utils/authNavigation";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/login",
      component: PlatformLoginPage,
      meta: { title: "平台管理端登录" },
    },
    {
      path: "/:tenantCode/login",
      component: TenantLoginPage,
      meta: { title: "租户登录" },
    },
    {
      path: "/:tenantCode/setup-password",
      component: TenantPasswordSetupPage,
      meta: { title: "租户管理员密码设置" },
    },
    {
      path: "/",
      component: AppLayout,
      children: [
        { path: "", redirect: "/dashboard" },
        { path: "/dashboard", component: TenantDashboardPage, meta: { title: "工作台" } },
        { path: "/profile", component: ProfilePage, meta: { title: "个人设置" } },
        { path: "/projects", component: ProjectPage, meta: { title: "项目管理" } },
        { path: "/meetings", component: MeetingPage, meta: { title: "会议管理" } },
        { path: "/audits", component: AuditPage, meta: { title: "审核管理" } },
        { path: "/finance", component: FinancePage, meta: { title: "财务管理" } },
        { path: "/users", component: UserPage, meta: { title: "用户管理" } },
        { path: "/tenants", component: TenantPage, meta: { title: "租户管理" } },
        { path: "/enterprises", component: EnterprisePage, meta: { title: "企业管理" } },
        { path: "/menus", component: MenuPage, meta: { title: "菜单与权限" } },
        { path: "/roles", component: RolePage, meta: { title: "角色管理" } },
        { path: "/permissions", redirect: { path: "/menus", query: { tab: "permissions" } } },
        { path: "/audit-flows", component: AuditFlowPage, meta: { title: "审核流配置" } },
        { path: "/data-permissions", component: DataPermissionPage, meta: { title: "数据权限管理" } },
        { path: "/templates", component: TemplatePage, meta: { title: "模板管理" } },
        { path: "/template-download-logs", component: TemplateDownloadLogPage, meta: { title: "模板查看下载" } },
        { path: "/audit-logs", component: AuditLogPage, meta: { title: "审计日志" } },
        { path: "/experts", component: ExpertPage, meta: { title: "专家管理" } },
        { path: "/invoice-profiles", component: InvoiceProfilePage, meta: { title: "发票管理" } },
        { path: "/export-tasks", component: ExportTaskPage, meta: { title: "导出任务中心" } },
        { path: "/notification-policies", component: NotificationPolicyPage, meta: { title: "通知策略中心" } },
        { path: "/notification-text-templates", component: NotificationTextTemplatePage, meta: { title: "通知文案模板" } },
        { path: "/in-app-notifications", component: InAppNotificationPage, meta: { title: "站内通知中心" } },
        { path: "/observability", component: ObservabilityPage, meta: { title: "可观测性与告警" } },
        { path: "/operations-dashboard", component: OperationsDashboardPage, meta: { title: "运营看板" } },
        { path: "/platform/tenants", component: TenantPage, meta: { title: "平台租户管理" } },
        { path: "/platform/audit-logs", component: AuditLogPage, meta: { title: "平台审计日志" } },
        { path: "/platform/menus", component: PlatformMenuPage, meta: { title: "平台菜单与权限" } },
        { path: "/platform/users", component: PlatformUserPage, meta: { title: "平台用户管理" } },
        { path: "/platform/roles", component: PlatformRolePage, meta: { title: "平台角色管理" } },
        { path: "/platform/dictionaries", component: PlatformDictionaryPage, meta: { title: "平台字典管理" } },
        { path: "/platform/auth-sessions", component: PlatformSessionPage, meta: { title: "平台会话管理" } },
        { path: "/platform/notify-gateways", component: PlatformNotifyGatewayPage, meta: { title: "通知网关配置" } },
        { path: "/platform/permissions", redirect: { path: "/platform/menus", query: { tab: "permissions" } } },
        { path: "/platform/experts", component: ExpertPage, meta: { title: "平台专家管理" } },
        { path: "/:pathMatch(.*)*", component: NotFoundPage, meta: { title: "页面未找到" } },
      ],
    },
  ],
});

router.beforeEach((to, _from, next) => {
  const authStore = useAuthStore(pinia);
  if (to.path === "/login" || /^\/[^/]+\/login$/.test(to.path) || /^\/[^/]+\/setup-password$/.test(to.path)) {
    return next();
  }
  const proceedWithTokenCheck = async () => {
    const token = authStore.token;
    if (!token) {
      try {
        const resp = await refreshAuth();
        const refreshedToken = String(resp?.data?.token || "").trim();
        if (!refreshedToken) {
          return next(resolveLoginPath(authStore.scope, authStore.tenantCode));
        }
        authStore.saveAuthPayload(resp?.data || null);
      } catch (_e) {
        return next(resolveLoginPath(authStore.scope, authStore.tenantCode));
      }
    }
    const scope = authStore.scope;
    const isPlatformPath = to.path.startsWith("/platform/");
    const isSharedProfilePath = to.path === "/profile";
    if (scope === "PLATFORM") {
      if (!isPlatformPath && !isSharedProfilePath) {
        return next("/platform/tenants");
      }
      return next();
    }
    if (to.path === "/audit-logs") {
      return next("/dashboard");
    }
    if (isPlatformPath) {
      return next("/dashboard");
    }
    next();
  };
  proceedWithTokenCheck();
});

router.afterEach((to) => {
  const meta = to.meta as Record<string, unknown> | undefined;
  const pageTitle = String(meta?.title || "").trim();
  document.title = pageTitle ? `${pageTitle} - 会议核销系统` : "会议核销系统";
});

export default router;
