import 'package:go_router/go_router.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../features/authentication/presentation/bloc/auth_bloc.dart';
import '../../features/authentication/presentation/pages/login_page.dart';
import 'main_navigation_layout.dart';

/// Configuration du routeur principal de l'application
class AppRouter {
  static final GoRouter router = GoRouter(
    initialLocation: '/',
    redirect: (context, state) {
      final authState = context.read<AuthBloc>().state;
      final isAuthenticated = authState is AuthAuthenticated;
      final isOnLoginPage = state.matchedLocation == '/login';

      // Si pas authentifié et pas sur la page de login, rediriger vers login
      if (!isAuthenticated && !isOnLoginPage) {
        return '/login';
      }

      // Si authentifié et sur la page de login, rediriger vers dashboard
      if (isAuthenticated && isOnLoginPage) {
        return '/';
      }

      return null; // Pas de redirection
    },
    routes: [
      GoRoute(
        path: '/login',
        name: 'login',
        builder: (context, state) => const LoginPage(),
      ),
      GoRoute(
        path: '/',
        name: 'main',
        builder: (context, state) => const MainNavigationLayout(),
      ),
    ],
  );
}
