/**
 * 应用路由配置
 * 
 * 路由结构：
 * - /login - 登录页（公开）
 * - /forgot-password - 忘记密码（公开）
 * - /reset-password - 重置密码（公开）
 * - /dashboard - 总览（需登录）
 * - /users - 用户管理（需管理员）
 * - /roles - 角色管理（需管理员）
 * - /permissions - 权限管理（需管理员）
 * - /logs/login - 登录日志（需管理员）
 * - /logs/operation - 操作日志（需管理员）
 * - /webhooks - Webhooks（需登录）
 * - /import-export - 导入导出（需管理员）
 * - /profile - 个人资料（需登录）
 * - /profile/security - 安全设置（需登录）
 */

import { createElement, lazy, type ComponentType, type LazyExoticComponent } from 'react'
import { createBrowserRouter, Navigate } from 'react-router-dom'
import { AdminLayout } from '@/layouts'
import { RootLayout } from './RootLayout'
// 路由守卫
import { RequireAuth, RequireAdmin } from '@/components/guards'

export function lazyPage<T extends ComponentType<object>>(
  loader: () => Promise<Record<string, unknown>>,
  exportName: string,
): LazyExoticComponent<T> {
  return lazy(async () => {
    const module = await loader()
    const component = module[exportName]
    if (typeof component !== 'function') {
      throw new Error(`lazy route export "${exportName}" is not a React component`)
    }
    return { default: component as T }
  })
}

function renderLazy<T extends ComponentType<object>>(Component: LazyExoticComponent<T>) {
  return createElement(Component)
}

const LoginPage = lazyPage(() => import('@/pages/auth/LoginPage'), 'LoginPage')
const RegisterPage = lazyPage(() => import('@/pages/auth/RegisterPage'), 'RegisterPage')
const BootstrapAdminPage = lazyPage(() => import('@/pages/auth/BootstrapAdminPage'), 'BootstrapAdminPage')
const ActivateAccountPage = lazyPage(() => import('@/pages/auth/ActivateAccountPage'), 'ActivateAccountPage')
const OAuthCallbackPage = lazyPage(() => import('@/pages/auth/OAuthCallbackPage'), 'OAuthCallbackPage')
const ForgotPasswordPage = lazyPage(() => import('@/pages/auth/ForgotPasswordPage'), 'ForgotPasswordPage')
const ResetPasswordPage = lazyPage(() => import('@/pages/auth/ResetPasswordPage'), 'ResetPasswordPage')

const DashboardPage = lazyPage(() => import('@/pages/admin/DashboardPage'), 'DashboardPage')
const UsersPage = lazyPage(() => import('@/pages/admin/UsersPage'), 'UsersPage')
const DevicesPage = lazyPage(() => import('@/pages/admin/DevicesPage'), 'DevicesPage')
const RolesPage = lazyPage(() => import('@/pages/admin/RolesPage'), 'RolesPage')
const PermissionsPage = lazyPage(() => import('@/pages/admin/PermissionsPage'), 'PermissionsPage')
const LoginLogsPage = lazyPage(() => import('@/pages/admin/LoginLogsPage'), 'LoginLogsPage')
const OperationLogsPage = lazyPage(() => import('@/pages/admin/OperationLogsPage'), 'OperationLogsPage')
const WebhooksPage = lazyPage(() => import('@/pages/admin/WebhooksPage'), 'WebhooksPage')
const ImportExportPage = lazyPage(() => import('@/pages/admin/ImportExportPage'), 'ImportExportPage')
const SettingsPage = lazyPage(() => import('@/pages/admin/SettingsPage'), 'SettingsPage')
const ProfilePage = lazyPage(() => import('@/pages/admin/ProfilePage'), 'ProfilePage')
const ProfileSecurityPage = lazyPage(() => import('@/pages/admin/ProfileSecurityPage'), 'ProfileSecurityPage')
const NotFoundPage = lazyPage(() => import('@/pages/NotFoundPage'), 'NotFoundPage')

export const router = createBrowserRouter(
  [
    // 根布局 - 提供 AuthProvider 上下文
    {
      element: <RootLayout />,
      children: [
        // 公开路由 - 认证页
        {
          path: '/login',
          element: renderLazy(LoginPage),
        },
        {
          path: '/register',
          element: renderLazy(RegisterPage),
        },
        {
          path: '/bootstrap-admin',
          element: renderLazy(BootstrapAdminPage),
        },
        {
          path: '/activate-account',
          element: renderLazy(ActivateAccountPage),
        },
        {
          path: '/login/oauth/callback',
          element: renderLazy(OAuthCallbackPage),
        },
        {
          path: '/forgot-password',
          element: renderLazy(ForgotPasswordPage),
        },
        {
          path: '/reset-password',
          element: renderLazy(ResetPasswordPage),
        },

        // 受保护路由 - 管理后台
        {
          path: '/',
          element: (
            <RequireAuth>
              <AdminLayout />
            </RequireAuth>
          ),
          children: [
            // 默认跳转到 Dashboard
            {
              index: true,
              element: <Navigate to="/dashboard" replace />,
            },
            
            // Dashboard - 需要登录
            {
              path: 'dashboard',
              element: (
                <RequireAdmin>
                  {renderLazy(DashboardPage)}
                </RequireAdmin>
              ),
            },

            // 管理功能 - 需要管理员权限
            {
              path: 'users',
              element: (
                <RequireAdmin>
                  {renderLazy(UsersPage)}
                </RequireAdmin>
              ),
            },
            {
              path: 'devices',
              element: (
                <RequireAdmin>
                  {renderLazy(DevicesPage)}
                </RequireAdmin>
              ),
            },
            {
              path: 'roles',
              element: (
                <RequireAdmin>
                  {renderLazy(RolesPage)}
                </RequireAdmin>
              ),
            },
            {
              path: 'permissions',
              element: (
                <RequireAdmin>
                  {renderLazy(PermissionsPage)}
                </RequireAdmin>
              ),
            },

            // 日志 - 需要管理员权限
            {
              path: 'logs/login',
              element: (
                <RequireAdmin>
                  {renderLazy(LoginLogsPage)}
                </RequireAdmin>
              ),
            },
            {
              path: 'logs/operation',
              element: (
                <RequireAdmin>
                  {renderLazy(OperationLogsPage)}
                </RequireAdmin>
              ),
            },

            // 集成能力
            {
              path: 'webhooks',
              element: renderLazy(WebhooksPage),
            },
            {
              path: 'import-export',
              element: (
                <RequireAdmin>
                  {renderLazy(ImportExportPage)}
                </RequireAdmin>
              ),
            },
            {
              path: 'settings',
              element: (
                <RequireAdmin>
                  {renderLazy(SettingsPage)}
                </RequireAdmin>
              ),
            },

            // 个人中心
            {
              path: 'profile',
              element: renderLazy(ProfilePage),
            },
            {
              path: 'profile/security',
              element: renderLazy(ProfileSecurityPage),
            },
          ],
        },

        // 404
        {
          path: '*',
          element: renderLazy(NotFoundPage),
        },
      ],
    },
  ],
)

