import 'package:dio/dio.dart';
import '../storage/token_storage.dart';

class ApiInterceptor extends Interceptor {
  final TokenStorage tokenStorage;
  final Dio dio;
  Future<bool> Function()? onTokenRefresh;

  ApiInterceptor({
    required this.tokenStorage,
    required this.dio,
    this.onTokenRefresh,
  });

  @override
  void onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) async {
    final token = await tokenStorage.getAccessToken();
    if (token != null) {
      options.headers['Authorization'] = 'Bearer $token';
    }
    handler.next(options);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    if (err.response?.statusCode == 401 && onTokenRefresh != null) {
      final refreshed = await onTokenRefresh!();
      if (refreshed) {
        final token = await tokenStorage.getAccessToken();
        if (token != null) {
          err.requestOptions.headers['Authorization'] = 'Bearer $token';
          try {
            final response = await dio.fetch(err.requestOptions);
            handler.resolve(response);
            return;
          } on DioException {
            // Retry failed, proceed with original error
          }
        }
      }
    }
    handler.next(err);
  }
}
