import { createRouter, createWebHistory } from 'vue-router'

const routes = [
    {
        path: '/login',
        name: 'login',
        component: () => import('../pages/auth/LoginPage.vue'),
        meta: { guest: true },
    },
    {
        path: '/auth/access',
        name: 'access-denied',
        component: () => import('../pages/pages/AccessDenied.vue'),
    },
    {
        path: '/auth/oops',
        name: 'oops',
        component: () => import('../pages/pages/Oops.vue'),
        meta: { guest: true },
    },
    {
        path: '/auth/error',
        name: 'error',
        component: () => import('../pages/pages/NotFound.vue'),
    },
    {
        path: '/',
        component: () => import('../layout/AppLayout.vue'),
        meta: { requiresAuth: true },
        children: [
            {
                path: '',
                name: 'dashboard',
                alias: '/dashboard',
                component: () => import('../pages/dashboard/DashboardPage.vue'),
            },
            {
                path: 'settings/activity-log',
                name: 'settings-activity-log',
                component: () => import('../pages/settings/activity-log/Index.vue'),
                meta: { permission: 'activitylog.view' },
            },
            {
                path: 'pages/oops',
                name: 'oops-authenticated',
                component: () => import('../pages/pages/Oops.vue'),
            },
            {
                path: 'pages/access-denied',
                name: 'pages-access-denied',
                component: () => import('../pages/pages/AccessDenied.vue'),
            },
            {
                path: 'pages/notfound',
                name: 'pages-notfound',
                component: () => import('../pages/pages/NotFound.vue'),
            },
        ],
    },
    {
        path: '/not-found',
        name: 'not-found',
        component: () => import('../pages/pages/NotFound.vue'),
    },
    {
        path: '/:pathMatch(.*)*',
        redirect: { name: 'not-found' },
    },
]

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

router.beforeEach((to) => {
    const isAuthenticated = !!localStorage.getItem('maestro_user')
    if (to.meta.requiresAuth && !isAuthenticated) {
        return { name: 'login', query: { redirect: to.fullPath } }
    }
    if (to.meta.guest && isAuthenticated) {
        return { name: 'dashboard' }
    }
})

export default router
