// middleware/auth.ts
import { useAuthSession } from '~/composables/useAuth';

export default defineNuxtRouteMiddleware(async (to) => {
  // This middleware should only run on the client-side after the initial server-side render.
  if (process.server) {
    return;
  }

  const { isLoggedIn, fetchUserSession } = useAuthSession();

  // Initial check
  if (!isLoggedIn.value) {
    await fetchUserSession();
  }

  // List of public routes that don't require authentication
  const publicRoutes = ['/auth/login', '/auth/register'];

  // If the route is not public and the user is not logged in, redirect to login
  if (!publicRoutes.includes(to.path) && !isLoggedIn.value) {
    return navigateTo('/auth/login');
  }
});
