import {
  createRouter,
  createWebHashHistory,
  type RouteRecordRaw,
} from "vue-router";

import { useUserStore } from "@/stores/UserStore.ts";

/**
 * Convert PascalCase to kebab-case and remove 'Page' suffix
 * @param name PascalCase name (e.g., AboutMePage)
 * @returns kebab-case path (e.g., about-me)
 */
function formatPathFromComponentName(name: string): string {
  // Remove .vue extension if present
  const baseName = name.endsWith(".vue") ? name.slice(0, -4) : name;

  // Remove Page suffix if present
  const withoutPageSuffix = baseName.endsWith("Page")
    ? baseName.slice(0, -4)
    : baseName;

  // Convert PascalCase to kebab-case
  return withoutPageSuffix
    .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
    .replace(/([A-Z])([A-Z][a-z])/g, "$1-$2")
    .toLowerCase();
}

/**
 * Extract component name from file path
 * @param filePath Path to the component file
 * @returns Component name without extension
 */
// function getComponentNameFromPath(filePath: string): string {
//   // Get the file name from the path
//   return filePath.split("/").pop() || "";
// }

/**
 * Generate route path from full file path, preserving directory structure
 * @param filePath Full path to the component file (e.g., "@/pages/test/AbcPage.vue")
 * @returns Route path (e.g., "/test/abc")
 */
function generateRoutePathFromFilePath(filePath: string): string {
  // Remove the "@/pages" prefix and get the relative path
  const relativePath = filePath.replace(/^@\/pages\//, "");

  // Split into directory parts and filename
  const pathParts = relativePath.split("/");
  const fileName = pathParts.pop() || "";
  const directories = pathParts.splice(3);

  // Transform the filename using existing logic
  const transformedFileName = formatPathFromComponentName(fileName);

  // Combine directory path with transformed filename
  const fullPath =
    directories.length > 0
      ? `/${directories.join("/")}/${transformedFileName}`
      : `/${transformedFileName}`;

  return fullPath;
}

/**
 * Generate routes from page components using Vite's import.meta.glob
 * @returns Array of route configurations
 */
function generateRoutesFromPages(): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = [];

  const pages = import.meta.glob("@/pages/**/*.vue");

  for (const path in pages) {
    // const componentName = getComponentNameFromPath(path);
    const routePath = generateRoutePathFromFilePath(path);

    // Special case for home page
    const finalPath = routePath.toLowerCase().endsWith("/home")
      ? routePath.slice(0, -5)
      : routePath;

    routes.push({
      path: finalPath,
      name: routePath,
      component: pages[path],
    });
  }

  return routes;
}

// Generate routes from pages directory
const routes: RouteRecordRaw[] = generateRoutesFromPages();

// 添加额外的路由配置，特别是带参数的路由
const extraRoutes: RouteRecordRaw[] = [
  {
    path: "/user/profile/:id",
    name: "UserProfile",
    component: () => import("@/pages/user/ProfilePage.vue"),
  },
  {
    path: "/product/detail/:id",
    name: "ProductDetail",
    component: () => import("@/pages/product/DetailPage.vue"),
  },
  {
    path: "/admin",
    redirect: "/admin/userManage",
  },
  {
    path: "/admin/userManage",
    name: "UserManage",
    component: () => import("@/pages/admin/UserPage.vue"),
    meta: { requiresAdmin: true }, // 添加管理员权限要求
  },
  {
    path: "/admin/category",
    name: "Categories",
    component: () => import("@/pages/admin/CategoryPage.vue"),
    meta: { requiresAdmin: true }, // 添加管理员权限要求
  },
  {
    path: "/admin/product",
    name: "Products",
    component: () => import("@/pages/admin/ProductPage.vue"),
    meta: { requiresAdmin: true }, // 添加管理员权限要求
  },
  {
    path: "/admin/order",
    name: "Orders",
    component: () => import("@/pages/admin/OrderPage.vue"),
    meta: { requiresAdmin: true }, // 添加管理员权限要求
  },
  // 可以在这里添加其他需要特殊配置的路由
];

// 合并自动生成的路由和额外的路由
const allRoutes = [...routes, ...extraRoutes];

const router = createRouter({
  history: createWebHashHistory(),
  routes: allRoutes,
  scrollBehavior(_to, _from, savedPosition) {
    // 如果有保存的位置（浏览器前进/后退），则使用保存的位置
    if (savedPosition) {
      return savedPosition;
    }
    // 否则滚动到顶部
    return { top: 0 };
  },
});

// 全局路由守卫 - 检查管理员权限
router.beforeEach((to, _from, next) => {
  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin) {
    const userStore = useUserStore();

    // 检查用户是否已登录
    if (!userStore.token || !userStore.userInfo) {
      // 未登录，跳转到登录页面
      next({
        name: "Login",
        query: { redirect: to.fullPath }, // 保存重定向路径
      });
      return;
    }

    // 检查用户是否为管理员
    if (userStore.userInfo.isAdmin !== 1) {
      // 不是管理员，跳转到首页或其他页面
      alert("您没有管理员权限！");
      next({ name: "Home" });
      return;
    }
  }

  next(); // 继续导航
});

export default router;
