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

// Type du layout choisi par App.vue : 'bare' (login, sans coquille),
// 'shell' (sidebar + contenu centré), 'fullbleed' (terminal plein écran dans la coquille).
declare module 'vue-router' {
  interface RouteMeta {
    layout?: 'bare' | 'shell' | 'fullbleed';
  }
}

export const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/login', name: 'login', component: () => import('../views/LoginView.vue'), meta: { layout: 'bare' } },
    { path: '/', name: 'dashboard', component: () => import('../views/DashboardView.vue'), meta: { layout: 'shell' } },
    { path: '/sessions', name: 'sessions', component: () => import('../views/SessionsListView.vue'), meta: { layout: 'shell' } },
    { path: '/sessions/:id', name: 'session', component: () => import('../views/SessionView.vue'), meta: { layout: 'fullbleed' } },
    { path: '/groups', name: 'groups', component: () => import('../views/GroupsListView.vue'), meta: { layout: 'shell' } },
    { path: '/groups/:id', name: 'group', component: () => import('../views/GroupView.vue'), meta: { layout: 'shell' } },
    { path: '/settings', name: 'settings', component: () => import('../views/SettingsView.vue'), meta: { layout: 'shell' } },
    { path: '/help', name: 'help', component: () => import('../views/HelpView.vue'), meta: { layout: 'shell' } },
    { 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 } };
});
