import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:go_router/go_router.dart';

import '../../features/auth/application/auth_service.dart';
import '../../features/login/presentation/pages/login_page.dart';
import '../../widgets/app_shell.dart';
import '../navigation/menu_route_definitions.dart';
import '../navigation/route_paths.dart';

/// 전역 네비게이터 키(로그인/셸 라우터 공용).
final _rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');

/// 애플리케이션 전체 라우팅 구성을 담당하는 GoRouter 인스턴스.
///
/// - 로그인 전용 라우트는 루트(primary) 네비게이터에서 처리한다.
/// - 로그인 이후 화면은 [ShellRoute] 하위에서 `AppShell` 레이아웃을 공유한다.
/// - 각 기능 모듈은 고유 name/path를 가지며 `GoRouter` 딥링크와 연결된다.
final appRouter = GoRouter(
  navigatorKey: _rootNavigatorKey,
  initialLocation: loginRoutePath,
  redirect: (context, state) {
    final authService = GetIt.I<AuthService>();
    final loggedIn = authService.session != null;
    final loggingIn = state.uri.path == loginRoutePath;
    if (!loggedIn && !loggingIn) {
      return loginRoutePath;
    }
    if (loggedIn && loggingIn) {
      return dashboardRoutePath;
    }
    return null;
  },
  routes: [
    GoRoute(path: '/', redirect: (_, __) => loginRoutePath),
    GoRoute(
      path: loginRoutePath,
      name: 'login',
      builder: (context, state) => const LoginPage(),
    ),
    ShellRoute(
      builder: (context, state, child) =>
          AppShell(currentLocation: state.uri.toString(), child: child),
      routes: [
        for (final definition in menuRouteDefinitions)
          GoRoute(
            path: definition.routePath,
            name: definition.menuCode,
            redirect: definition.buildGuard(),
            builder: definition.builder,
          ),
      ],
    ),
  ],
);
