import 'dart:developer';

import 'package:auto_route/auto_route.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../presentation/router/app_router.gr.dart';
import '../../constant/local_storage_key.dart';
import '../errors/unauthorized_error.dart';

class UnauthorizedInterceptor extends Interceptor {
  static final GlobalKey<NavigatorState> navigatorKey =
      GlobalKey<NavigatorState>();
  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    if (err.response?.statusCode == 401 ||
        err.response?.statusCode == 403 ||
        err.response?.statusCode == 419) {
      await _handleTokenExpired();
      return super.onError(UnauthorizedError(err, null), handler);
    }
    super.onError(err, handler);
  }

  Future<void> _handleTokenExpired() async {
    // Clear stored token
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(LocalStorageKey.token);
    await prefs.remove(LocalStorageKey.user);
    await prefs.clear(); // Optional: clear all user data
    log('handleTokenExpired');
    // Navigate to login page
    final context = navigatorKey.currentContext;
    if (context != null) {
      // Option 1: Navigate and remove all previous routes
      context.router.replaceAll([LoginRoute()]);
    }
  }
}
