import { Navigate, createBrowserRouter } from 'react-router-dom';
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import Silkworm from './pages/Silkworm';
import Device from './pages/Device';
import Energy from './pages/Energy';
import Control from './pages/Control';
import IRControl from './pages/IRControl';
import Threshold from './pages/Threshold';
import Alert from './pages/Alert';
import Video from './pages/Video';
import Log from './pages/Log';
import Knowledge from './pages/Knowledge';
import Batches from './pages/Batches';
import NotFound from './pages/NotFound';
import { BasicLayout } from './layout/BasicLayout';
import { authService } from './services/auth';

const RequireAuth = ({ children }: { children: React.ReactNode }) => {
  if (!authService.isLoggedIn()) return <Navigate to="/login" replace />;
  return <>{children}</>;
};

// 路由权限守卫：未登录跳登录页，无权限跳仪表盘
const RequirePermission = ({ permission, children }: { permission: string; children: React.ReactNode }) => {
  if (!authService.isLoggedIn()) return <Navigate to="/login" replace />;
  if (!authService.hasPermission(permission)) return <Navigate to="/dashboard" replace />;
  return <>{children}</>;
};

export const router = createBrowserRouter([
  { path: '/login', element: <Login /> },
  {
    element: (
      <RequireAuth>
        <BasicLayout />
      </RequireAuth>
    ),
    children: [
      { index: true, element: <Navigate to="/dashboard" replace /> },
      { path: 'dashboard', element: <RequirePermission permission="dashboard:view"><Dashboard /></RequirePermission> },
      { path: 'houses', element: <RequirePermission permission="room:read"><Silkworm /></RequirePermission> },
      { path: 'devices', element: <RequirePermission permission="device:read"><Device /></RequirePermission> },
      { path: 'energy', element: <RequirePermission permission="energy:view"><Energy /></RequirePermission> },
      { path: 'control', element: <RequirePermission permission="device:control"><Control /></RequirePermission> },
      { path: 'ir', element: <RequirePermission permission="device:control"><IRControl /></RequirePermission> },
      { path: 'thresholds', element: <RequirePermission permission="threshold:read"><Threshold /></RequirePermission> },
      { path: 'alerts', element: <RequirePermission permission="alarm:read"><Alert /></RequirePermission> },
      { path: 'videos', element: <RequirePermission permission="video:read"><Video /></RequirePermission> },
      { path: 'logs', element: <RequirePermission permission="log:read"><Log /></RequirePermission> },
      { path: 'knowledge', element: <RequirePermission permission="knowledge:read"><Knowledge /></RequirePermission> },
      { path: 'batches', element: <RequirePermission permission="batch:read"><Batches /></RequirePermission> },
      { path: '404', element: <NotFound /> },
    ],
  },
  { path: '*', element: <NotFound /> },
]);
