import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/views/Layout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: '/dashboard'
      },
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '控制台' }
      },
      {
        path: 'tenants',
        name: 'Tenants',
        component: () => import('@/views/tenants/TenantList.vue'),
        meta: { title: '租户管理' }
      },
      {
        path: 'tenants/:id',
        name: 'TenantDetail',
        component: () => import('@/views/tenants/TenantDetail.vue'),
        meta: { title: '租户详情' }
      },
      {
        path: 'tenants/:id/configs',
        name: 'TenantConfigs',
        component: () => import('@/views/tenants/TenantConfigs.vue'),
        meta: { title: '租户配置' }
      },
      {
        path: 'tenants/:id/features',
        name: 'TenantFeatures',
        component: () => import('@/views/tenants/TenantFeatures.vue'),
        meta: { title: '功能开关' }
      },
      {
        path: 'prompts',
        name: 'Prompts',
        component: () => import('@/views/prompts/PromptList.vue'),
        meta: { title: '提示词管理' }
      },
      {
        path: 'prompts/:id',
        name: 'PromptDetail',
        component: () => import('@/views/prompts/PromptDetail.vue'),
        meta: { title: '提示词详情' }
      },
      {
        path: 'logs',
        name: 'Logs',
        component: () => import('@/views/Logs.vue'),
        meta: { title: '操作日志' }
      },
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue')
  }
]

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

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  if (to.meta.requiresAuth !== false && !authStore.isLoggedIn) {
    next({ name: 'Login', query: { redirect: to.fullPath } })
  } else if (to.name === 'Login' && authStore.isLoggedIn) {
    next({ name: 'Dashboard' })
  } else {
    next()
  }
})

export default router

