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

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
    },
    {
      path: '/',
      component: Layout,
      redirect: '/dashboard',
      children: [
        { path: 'dashboard', name: 'dashboard', component: () => import('@/views/DashboardView.vue') },
        { path: 'egress/providers', name: 'providers', component: () => import('@/views/ProvidersView.vue') },
        { path: 'ingress/keys', name: 'ingress-keys', component: () => import('@/views/IngressKeysView.vue') },
        {
          path: 'ingress/docs/text',
          name: 'ingress-api-doc-text',
          component: () => import('@/views/IngressApiDocView.vue'),
          props: { protocol: 'text' },
        },
        {
          path: 'ingress/docs/image',
          name: 'ingress-api-doc-image',
          component: () => import('@/views/IngressApiDocView.vue'),
          props: { protocol: 'image' },
        },
        { path: 'logs', name: 'logs', component: () => import('@/views/RequestLogsView.vue') },
        { path: 'security/ip-rules', name: 'ip-rules', component: () => import('@/views/IPRulesView.vue') },
        { path: 'security/settings', name: 'settings', component: () => import('@/views/SettingsView.vue') },
      ],
    },
  ],
})

router.beforeEach(async (to) => {
  if (to.name === 'login') return true
  try {
    const res = await fetch('/api/admin/auth/status', { credentials: 'include' })
    const data = await res.json()
    if (!data.authenticated) return '/login'
  } catch {
    return '/login'
  }
  return true
})

export default router
