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

// Define your routes here
const routes = [
    {
        path: '/',
        name: 'Home',
        component: () => import('./pages/HomePage.vue')
    },
    {
        path: '/medias',
        name: 'Medias',
        component: () => import('./pages/MediaPage.vue')
    },
    {
        path: '/medias/uploads',
        name: 'Uploads',
        component: () => import('./pages/MediaUploadPage.vue')
    },
    {
        path: '/posts',
        name: 'Posts',
        component: () => import('./pages/PostPage.vue'),
    },
    // Add route for post creation
    {
        path: '/posts/create',
        name: 'CreatePost',
        component: () => import('./pages/PostCreatePage.vue')
    },
    // Add route for post editing
    {
        path: '/posts/edit/:id',
        name: 'EditPost',
        component: () => import('./pages/PostEditPage.vue'),
        props: true
    },
    {
        path: '/users',
        name: 'Users',
        component: () => import('./pages/UserPage.vue'),
    },
    {
        path: '/users/:id',
        name: 'UserDetail',
        component: () => import('./pages/UserDetail.vue'),
        props: true
    },
    {
        path: '/orders',
        name: 'Orders',
        component: () => import('./pages/OrderPage.vue'),
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('./pages/LoginPage.vue'),
        meta: { requiresAuth: false }
    }
];

// Create the router instance
export const router = createRouter({
    history: createWebHistory("/admin/"), // Use createWebHashHistory() if you want hash-based routing
    // history: createWebHashHistory(),
    routes
});

// Add navigation guard
router.beforeEach((to, from, next) => {
    const authStore = useAuthStore();

    if (to.meta.requiresAuth !== false && !authStore.isAuthenticated) {
        next('/login');
    } else if (to.path === '/login' && authStore.isAuthenticated) {
        next('/');
    } else {
        next();
    }
});
