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

export const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/login', name: 'login', component: () => import('../views/LoginView.vue') },
    { path: '/', name: 'dashboard', component: () => import('../views/DashboardView.vue') },
    { path: '/sessions', name: 'sessions', component: () => import('../views/SessionsListView.vue') },
    { path: '/sessions/:id', name: 'session', component: () => import('../views/SessionView.vue') },
    { path: '/:pathMatch(.*)*', redirect: '/' },
  ],
});

// Garde globale : tout sauf /login exige une session valide (GET /api/v1/auth/me, 401 → /login)
router.beforeEach(async (to) => {
  const auth = useAuthStore();
  if (auth.authenticated === null) await auth.check();
  if (to.name === 'login') return auth.authenticated ? { name: 'dashboard' } : true;
  return auth.authenticated ? true : { name: 'login', query: { redirect: to.fullPath } };
});
