import { createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import BasicLayout from '@/layout/BasicLayout.vue';
import { useUserStore } from '@/stores/user';

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/Login.vue'),
    meta: { public: true, title: '登录' },
  },
  {
    path: '/',
    component: BasicLayout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/Dashboard.vue'),
        meta: { title: '仪表盘', icon: 'Odometer' },
      },
      {
        path: 'devices',
        name: 'Devices',
        component: () => import('@/views/devices/DeviceList.vue'),
        meta: { title: '设备管理', icon: 'Monitor' },
      },
      {
        path: 'connections',
        name: 'Connections',
        component: () => import('@/views/connections/ConnectionList.vue'),
        meta: { title: '连接请求', icon: 'Connection' },
      },
      {
        path: 'system/info',
        name: 'SystemInfo',
        component: () => import('@/views/system/ServerInfo.vue'),
        meta: { title: '服务器信息', icon: 'Cpu' },
      },
      {
        path: 'system/config',
        name: 'SystemConfig',
        component: () => import('@/views/system/Settings.vue'),
        meta: { title: '系统配置', icon: 'Setting' },
      },
    ],
  },
  { path: '/:pathMatch(.*)*', redirect: '/dashboard' },
];

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

router.beforeEach((to) => {
  const user = useUserStore();
  const token = user.token || localStorage.getItem('admin_token');
  if (!to.meta.public && !token) {
    return { name: 'Login', query: { redirect: to.fullPath } };
  }
  if (to.name === 'Login' && token) {
    return { name: 'Dashboard' };
  }
  return true;
});

export default router;
