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

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
      meta: { public: true },
    },
    {
      path: '/',
      component: MainLayout,
      children: [
        { path: '', name: 'dashboard', component: () => import('@/views/DashboardView.vue') },
        { path: 'subscriptions', name: 'subscriptions', component: () => import('@/views/SubscriptionsView.vue') },
        { path: 'proxies', name: 'proxies', component: () => import('@/views/ProxiesView.vue') },
        { path: 'outbound', name: 'outbound', component: () => import('@/views/OutboundView.vue') },
        { path: 'rules', name: 'rules', component: () => import('@/views/RulesView.vue') },
        { path: 'traffic-logs', name: 'traffic-logs', component: () => import('@/views/TrafficLogsView.vue') },
        { path: 'logs', name: 'logs', component: () => import('@/views/LogsView.vue') },
        { path: 'settings', name: 'settings', component: () => import('@/views/SettingsView.vue') },
      ],
    },
  ],
})

router.beforeEach(async (to) => {
  const auth = useAuthStore()
  if (to.meta.public) return true
  if (auth.isLoggedIn()) return true
  try {
    const res = await fetch('/api/v1/auth/status')
    const data = await res.json()
    if (!data.enabled) {
      auth.token = 'disabled'
      return true
    }
  } catch { /* ignore */ }
  return '/login'
})

export default router
