import { createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { useServerStore } from '@/stores/server';

const routes: RouteRecordRaw[] = [
  {
    path: '/server-config',
    name: 'ServerConfig',
    component: () => import('@/views/ServerConfig/index.vue'),
    meta: { requiresAuth: false },
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login/index.vue'),
    meta: { requiresAuth: false },
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register/index.vue'),
    meta: { requiresAuth: false },
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard/index.vue'),
      },
      {
        path: 'accounts',
        name: 'Accounts',
        component: () => import('@/views/Accounts/index.vue'),
      },
      {
        path: 'works',
        name: 'Works',
        component: () => import('@/views/Works/index.vue'),
      },
      {
        path: 'publish',
        name: 'Publish',
        component: () => import('@/views/Publish/index.vue'),
      },
      {
        path: 'comments',
        name: 'Comments',
        component: () => import('@/views/Comments/index.vue'),
      },
      {
        path: 'schedule',
        name: 'Schedule',
        component: () => import('@/views/Schedule/index.vue'),
      },
      {
        path: 'analytics',
        name: 'Analytics',
        redirect: '/analytics/overview',
        children: [
          {
            path: 'overview',
            name: 'AnalyticsOverview',
            component: () => import('@/views/Analytics/Overview/index.vue'),
          },
          {
            path: 'platform',
            name: 'AnalyticsPlatform',
            component: () => import('@/views/Analytics/Platform/index.vue'),
          },
          {
            path: 'platform-detail/:platform',
            name: 'AnalyticsPlatformDetail',
            component: () => import('@/views/Analytics/PlatformDetail/index.vue'),
          },
          {
            path: 'account',
            name: 'AnalyticsAccount',
            component: () => import('@/views/Analytics/Account/index.vue'),
          },
          {
            path: 'work',
            name: 'AnalyticsWork',
            component: () => import('@/views/Analytics/Work/index.vue'),
          },
        ],
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('@/views/Settings/index.vue'),
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile/index.vue'),
      },
    ],
  },
];

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

// 标记是否已初始化认证状态
let authInitialized = false;

// 路由守卫
router.beforeEach(async (to, _from, next) => {
  const authStore = useAuthStore();
  const serverStore = useServerStore();
  
  // 加载服务器配置（同步操作）
  if (!serverStore.isConfigured) {
    serverStore.loadConfig();
  }
  
  // 检查服务器配置
  if (!serverStore.isConfigured && to.name !== 'ServerConfig') {
    next({ name: 'ServerConfig' });
    return;
  }
  
  // 首次进入需要认证的页面时，先检查认证状态
  if (!authInitialized && serverStore.isConfigured) {
    authInitialized = true;
    await authStore.checkAuth();
  }
  
  // 检查认证
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    next({ name: 'Login' });
    return;
  }
  
  // 已登录用户不能访问登录/注册页
  if (authStore.isAuthenticated && ['Login', 'Register'].includes(to.name as string)) {
    next({ name: 'Dashboard' });
    return;
  }
  
  next();
});

export default router;
