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

const router = createRouter({
  history: createWebHistory('/app/'),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
      meta: { guest: true }
    },
    {
      path: '/register',
      name: 'register-org',
      component: () => import('@/views/RegisterOrgView.vue'),
      meta: { guest: true }
    },
    {
      path: '/admin',
      name: 'admin',
      component: () => import('@/views/AdminDashboardView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/',
      component: () => import('@/components/layout/AppLayout.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'dashboard',
          component: () => import('@/views/DashboardView.vue')
        },
        {
          path: 'orders',
          name: 'orders',
          component: () => import('@/views/OrdersView.vue')
        },
        {
          path: 'orders/:id',
          name: 'order-detail',
          component: () => import('@/views/OrderDetailView.vue')
        },
        {
          path: 'users',
          name: 'users',
          component: () => import('@/views/UsersView.vue'),
          meta: { roles: ['chef', 'disponent'] }
        },
        {
          path: 'availability',
          name: 'availability',
          component: () => import('@/views/AvailabilityView.vue')
        },
        {
          path: 'timesheets',
          name: 'timesheets',
          component: () => import('@/views/TimesheetsView.vue')
        },
        {
          path: 'settings',
          name: 'settings',
          component: () => import('@/views/SettingsView.vue')
        },
        {
          path: 'modules',
          name: 'modules',
          component: () => import('@/views/ModulesView.vue'),
          meta: { roles: ['chef'] }
        },
        {
          path: 'partnerships',
          name: 'partnerships',
          component: () => import('@/views/PartnershipsView.vue')
        },
        {
          path: 'help',
          name: 'help',
          component: () => import('@/views/HelpView.vue')
        },
        {
          path: 'qualifications',
          name: 'qualifications',
          component: () => import('@/views/QualificationsView.vue')
        },
        {
          path: 'objects',
          name: 'objects',
          component: () => import('@/views/ObjectsView.vue')
        }
      ]
    }
  ]
})

router.beforeEach(async (to, _from, next) => {
  const authStore = useAuthStore()
  
  // Try to restore session
  if (!authStore.isAuthenticated && authStore.hasStoredToken) {
    await authStore.fetchCurrentUser()
  }
  
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const isGuest = to.matched.some(record => record.meta.guest)
  const requiredRoles = to.meta.roles as string[] | undefined
  
  if (requiresAuth && !authStore.isAuthenticated) {
    next({ name: 'login', query: { redirect: to.fullPath } })
  } else if (isGuest && authStore.isAuthenticated) {
    next({ name: 'dashboard' })
  } else if (requiredRoles && !requiredRoles.includes(authStore.user?.role || '')) {
    next({ name: 'dashboard' })
  } else {
    next()
  }
})

export default router
