import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:pyramid/features/auth/login_notifier.dart';
import 'package:pyramid/features/auth/login_page.dart';
import 'package:pyramid/features/auth/server_page.dart';
import 'package:pyramid/layout/app_shell.dart';

final routerProvider = Provider<GoRouter>((ref) {
  final isLoggedIn = ref.watch(isLoggedInProvider).valueOrNull ?? false;
  final hasServer = ref.watch(homeserverProvider) != null;

  return GoRouter(
    initialLocation: '/app',
    redirect: (context, state) {
      final loc = state.matchedLocation;
      final onAuth = loc == '/login' || loc == '/server';

      if (!isLoggedIn) {
        if (!hasServer && loc != '/server') return '/server';
        if (hasServer && loc != '/login' && !onAuth) return '/login';
        return null;
      }

      if (isLoggedIn && onAuth) return '/app';
      return null;
    },
    routes: [
      GoRoute(
        path: '/server',
        builder: (context, state) => const ServerPage(),
      ),
      GoRoute(
        path: '/login',
        builder: (context, state) => const LoginPage(),
      ),
      GoRoute(
        path: '/app',
        builder: (context, state) => const AppShell(),
      ),
    ],
  );
});
