import 'package:go_router/go_router.dart';
import 'package:http/http.dart' as http;
import 'package:fotodocumentation/utils/di_container.dart';
import 'package:fotodocumentation/utils/login_credentials.dart';
import 'package:fotodocumentation/utils/global_router.dart';

/// HTTP client that intercepts all responses and handles 401 status codes
/// by logging out the user and redirecting to the login page.
class HttpClientInterceptor extends http.BaseClient {
  final http.Client _inner;

  HttpClientInterceptor(this._inner);

  @override
  Future<http.StreamedResponse> send(http.BaseRequest request) async {
    final response = await _inner.send(request);

    // Check for 401 Unauthorized
    if (response.statusCode == 401) {
      _handle401Unauthorized();
    }

    return response;
  }

  void _handle401Unauthorized() {
    // Clear login credentials
    final loginCredentials = DiContainer.get<LoginCredentials>();
    loginCredentials.logout();

    // Navigate to login page using GoRouter
    final context = GlobalRouter.rootNavigatorKey.currentContext;
    if (context != null) {
      context.go(GlobalRouter.pathLogin);
    }
  }
}