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

// Layouts
import GuestLayout from '../layouts/GuestLayout.vue';
import AuthLayout from '../layouts/AuthLayout.vue';
import WorkerLayout from '../layouts/WorkerLayout.vue';
import ClientLayout from '../layouts/ClientLayout.vue';
import AdminLayout from '../layouts/AdminLayout.vue';

// Views
import Login from '../views/Auth/Login.vue';
import Register from '../views/Auth/Register.vue';
import ForgotPassword from '../views/Auth/ForgotPassword.vue';
import ResetPassword from '../views/Auth/ResetPassword.vue';
import WorkerDashboard from '../views/Worker/Dashboard.vue';
import ClientDashboard from '../views/Client/Dashboard.vue';
import AdminDashboard from '../views/Admin/Dashboard.vue';
import Home from '../views/Home.vue';
import NotFound from '../views/NotFound.vue';

const routes = [
    {
        path: '/',
        component: GuestLayout,
        children: [
            { path: '', name: 'home', component: Home },
        ]
    },
    {
        path: '/',
        component: AuthLayout,
        children: [
            { path: 'login', name: 'login', component: Login },
            { path: 'register', name: 'register', component: Register },
            { path: 'forgot-password', name: 'forgot-password', component: ForgotPassword },
            { path: 'password-reset/:token', name: 'password-reset', component: ResetPassword },
        ]
    },
    {
        path: '/worker',
        component: WorkerLayout,
        meta: { requiresAuth: true, role: 'worker' },
        children: [
            { path: 'dashboard', name: 'worker.dashboard', component: WorkerDashboard },
        ]
    },
    {
        path: '/client',
        component: ClientLayout,
        meta: { requiresAuth: true, role: 'client' },
        children: [
            { path: 'dashboard', name: 'client.dashboard', component: ClientDashboard },
        ]
    },
    {
        path: '/admin',
        component: AdminLayout,
        meta: { requiresAuth: true, role: 'admin' },
        children: [
            { path: 'dashboard', name: 'admin.dashboard', component: AdminDashboard },
            { path: 'settings', name: 'admin.settings', component: () => import('../views/Admin/Settings.vue') },
        ]
    },
    { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },
];

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

import { useAuthStore } from '../stores/auth';

router.beforeEach(async (to, from, next) => {
    const authStore = useAuthStore();

    // Check if user is authenticated (token exists)
    const isAuthenticated = authStore.token;

    if (to.meta.requiresAuth && !isAuthenticated) {
        next({ name: 'login' });
    } else if (isAuthenticated && (to.name === 'login' || to.name === 'register')) {
        // Redirect to appropriate dashboard if already logged in
        if (authStore.user?.role === 'worker') next({ name: 'worker.dashboard' });
        else if (authStore.user?.role === 'client') next({ name: 'client.dashboard' });
        else if (authStore.user?.role === 'admin') next({ name: 'admin.dashboard' });
        else next();
    } else {
        // Role check
        if (to.meta.role && authStore.user?.role !== to.meta.role) {
            // Simple check: if user info missing, maybe fetch it? 
            // For now, if role mismatch, redirect home or show error
            // Check if user object is loaded. If token exists but user is null, try fetch?
            if (!authStore.user) {
                try {
                    await authStore.fetchUser();
                    if (authStore.user?.role === to.meta.role) next();
                    else next({ name: 'home' }); // Unauthorized
                } catch (e) {
                    authStore.logout();
                    next({ name: 'login' });
                }
            } else {
                next({ name: 'home' });
            }
        } else {
            next();
        }
    }
});

export default router;
