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

export default defineNuxtRouteMiddleware((to) => {
  const authStore = useAuthStore();

  // Public routes (set via definePageMeta({ public: true }) in each page)
  if (to.meta.public === true) {
    // Redirect already-authenticated users away from /login
    if (to.path === '/login' && authStore.currentUser) {
      return navigateTo('/');
    }
    return;
  }

  // All other routes require auth
  if (!authStore.currentUser) {
    return navigateTo('/login');
  }

  // Role-based access: pages set requiredRoles via definePageMeta
  const requiredRoles = to.meta.requiredRoles as string[] | undefined;
  if (requiredRoles && requiredRoles.length > 0) {
    if (!authStore.hasRequiredRole(requiredRoles)) {
      return abortNavigation();
    }
  }
});
