// 管理后台路由配置，负责页面注册、默认入口和登录访问控制。
import { createRouter, createWebHistory } from "vue-router";
import { DEFAULT_ADMIN_PATH } from "@/router/adminNavigation";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: "/login", name: "login", component: () => import("@/views/LoginView.vue"), meta: { public: true } },
    {
      path: "/",
      component: () => import("@/layouts/AdminLayout.vue"),
      children: [
        { path: "", redirect: DEFAULT_ADMIN_PATH },
        {
          path: "redemption-codes",
          name: "redemption-codes",
          component: () => import("@/views/RedemptionsView.vue"),
          meta: { title: "兑换码管理" },
        },
        {
          path: "styles",
          name: "styles",
          component: () => import("@/views/StylesView.vue"),
          meta: { title: "风格管理" },
        },
        {
          path: "prompts",
          name: "prompts",
          component: () => import("@/views/PromptsView.vue"),
          meta: { title: "提示词管理" },
        },
        {
          path: "channels",
          name: "channels",
          component: () => import("@/views/ChannelsView.vue"),
          meta: { title: "渠道管理" },
        },
        {
          path: "models",
          name: "models",
          component: () => import("@/views/ModelsView.vue"),
          meta: { title: "模型管理" },
        },
        {
          path: "users",
          name: "users",
          component: () => import("@/views/UsersView.vue"),
          meta: { title: "用户管理" },
        },
        {
          path: "audit-logs",
          name: "audit-logs",
          component: () => import("@/views/AuditLogsView.vue"),
          meta: { title: "审计日志" },
        },
        {
          path: "security",
          name: "security",
          component: () => import("@/views/SecurityView.vue"),
          meta: { title: "账号安全" },
        },
      ],
    },
    { path: "/:pathMatch(.*)*", redirect: DEFAULT_ADMIN_PATH },
  ],
});

router.beforeEach((to) => {
  const authenticated = Boolean(localStorage.getItem("admin_access_token"));
  if (!to.meta.public && !authenticated) return { name: "login", query: { redirect: to.fullPath } };
  if (to.name === "login" && authenticated) return { path: DEFAULT_ADMIN_PATH };
  document.title = "剧游AI-后台管理";
  return true;
});

export default router;
