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

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/Login.vue'),
      meta: { requiresAuth: false },
    },
    {
      path: '/',
      component: () => import('../views/Layout.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'Dashboard',
          component: () => import('../views/Dashboard.vue'),
        },
        {
          path: 'memory',
          name: 'Memory',
          component: () => import('../views/Memory.vue'),
        },
        {
          path: 'barcodes',
          name: 'Barcodes',
          component: () => import('../views/Barcodes.vue'),
        },
        {
          path: 'config',
          name: 'Config',
          component: () => import('../views/Config.vue'),
        },
        {
          path: 'sync',
          name: 'Sync',
          component: () => import('../views/Sync.vue'),
        },
        {
          path: 'tasks',
          name: 'Tasks',
          component: () => import('../views/Tasks.vue'),
        },
        {
          path: 'logs',
          name: 'Logs',
          component: () => import('../views/Logs.vue'),
        },
        {
          path: 'files',
          redirect: '/files/orders',
        },
        {
          path: 'files/orders',
          name: 'FilesOrders',
          component: () => import('../views/files/Orders.vue'),
        },
        {
          path: 'files/tables',
          name: 'FilesTables',
          component: () => import('../views/files/Tables.vue'),
        },
        {
          path: 'files/images',
          name: 'FilesImages',
          component: () => import('../views/files/Images.vue'),
        },
      ],
    },
  ],
})

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  if (to.meta.requiresAuth !== false && !authStore.isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

export default router
