import {
  Coin,
  DataAnalysis,
  Document,
  House,
  OfficeBuilding,
  Operation,
  PriceTag,
  Setting,
  Tickets,
  UserFilled,
} from '@element-plus/icons-vue';
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';
import { useAuthStore } from './stores/auth';

export const routes: RouteRecordRaw[] = [
  { path: '/', redirect: '/dashboard' },
  {
    path: '/auth/login',
    component: () => import('./views/LoginView.vue'),
    meta: { public: true },
  },
  {
    path: '/dashboard',
    component: () => import('./views/DashboardView.vue'),
    meta: { title: '仪表盘', icon: DataAnalysis },
  },
  {
    path: '/tenants',
    component: () => import('./views/TenantListView.vue'),
    meta: { title: '租户管理', icon: OfficeBuilding },
  },
  {
    path: '/tenants/:id',
    component: () => import('./views/TenantDetailView.vue'),
    meta: { title: '租户详情', hidden: true, icon: House },
  },
  {
    path: '/users',
    component: () => import('./views/UserManagementView.vue'),
    meta: { title: '用户管理', icon: UserFilled },
  },
  {
    path: '/billing/records',
    component: () => import('./views/BillingRecordsView.vue'),
    meta: { title: '计费记录', icon: Coin },
  },
  {
    path: '/billing/costs',
    component: () => import('./views/BillingCostsView.vue'),
    meta: { title: '计费价格', icon: PriceTag, authority: ['SUPER_ADMIN'] },
  },
  {
    path: '/model-config',
    component: () => import('./views/ModelConfigView.vue'),
    meta: { title: '模型配置', icon: Setting, authority: ['SUPER_ADMIN', 'OPERATOR'] },
  },
  {
    path: '/plans',
    component: () => import('./views/PlanManagementView.vue'),
    meta: { title: '套餐管理', icon: PriceTag, authority: ['SUPER_ADMIN'] },
  },
  {
    path: '/admin-users',
    component: () => import('./views/AdminUserManagementView.vue'),
    meta: { title: '运营人员', icon: Operation, authority: ['SUPER_ADMIN'] },
  },
  {
    path: '/audit-logs',
    component: () => import('./views/AuditLogsView.vue'),
    meta: { title: '审计日志', icon: Tickets },
  },
  {
    path: '/:pathMatch(.*)*',
    component: () => import('./views/NotFoundView.vue'),
    meta: { title: '未找到', hidden: true, icon: Document },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach((to) => {
  const auth = useAuthStore();
  if (to.meta.public) return true;
  if (!auth.isLoggedIn) return '/auth/login';
  const authority = to.meta.authority as string[] | undefined;
  if (!auth.hasRole(authority)) return '/dashboard';
  return true;
});

export default router;
