import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { useAuthStore } from '../stores/auth';
import LoginView from '../views/LoginView.vue';
import AppLayout from '../layouts/AppLayout.vue';
import DashboardView from '../views/dashboard/DashboardView.vue';
import MapView from '../views/map/MapView.vue';
import MapFullscreenView from '../views/map/MapFullscreenView.vue';
import LampsView from '../views/lamps/LampsView.vue';
import TerminalsView from '../views/terminals/TerminalsView.vue';
import SyncView from '../views/sync/SyncView.vue';
import AlarmsView from '../views/alarms/AlarmsView.vue';
import UsersView from '../views/system/UsersView.vue';
import RolesView from '../views/system/RolesView.vue';
import TenantsView from '../views/system/TenantsView.vue';

export const menuRoutes: RouteRecordRaw[] = [
  { path: '/system/tenants', component: TenantsView, meta: { title: '租户管理', permission: 'tenants:manage' } },
  { path: '/dashboard', component: DashboardView, meta: { title: '总览', permission: 'dashboard:view' } },
  { path: '/map', component: MapView, meta: { title: '设备监控', permission: 'map:view' } },
  { path: '/lamps', component: LampsView, meta: { title: '路灯资产', permission: 'lamps:manage' } },
  { path: '/terminals', component: TerminalsView, meta: { title: '监控终端', permission: 'lamps:manage' } },
  { path: '/sync', component: SyncView, meta: { title: '运维管理', permission: 'lamps:manage' } },
  { path: '/alarms', component: AlarmsView, meta: { title: '告警管理', permission: 'alarms:manage' } },
  { path: '/system/users', component: UsersView, meta: { title: '用户管理', permission: 'system:manage' } },
  { path: '/system/roles', component: RolesView, meta: { title: '角色权限', permission: 'system:manage' } },
];

export function firstPermittedPath(permissions: string[]) {
  return menuRoutes.find((route) => {
    const permission = route.meta?.permission as string | undefined;
    return !permission || permissions.includes(permission);
  })?.path ?? '/login';
}

export const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/login', component: LoginView },
    { path: '/map/fullscreen', component: MapFullscreenView, meta: { title: '全屏地图', permission: 'map:view' } },
    {
      path: '/',
      component: AppLayout,
      redirect: '/dashboard',
      children: menuRoutes,
    },
  ],
});

router.beforeEach((to) => {
  const token = localStorage.getItem('accessToken');
  if (to.path !== '/login' && !token) {
    return '/login';
  }

  const permission = to.meta.permission as string | undefined;
  const authStore = useAuthStore();
  if (permission && authStore.permissions.length && !authStore.permissions.includes(permission)) {
    return firstPermittedPath(authStore.permissions);
  }

  return true;
});
