import 'package:dio/dio.dart';
import '../../configs/constants.dart';
import '../app_navigator.dart';
import 'package:mypoint_flutter_app/preference/data_preference.dart';

class AuthInterceptor extends Interceptor {
  bool _isHandlingAuth = false;

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    final data = response.data;
    if (_isTokenInvalid(data)) {
      _handleAuthError(data);
      handler.reject(
        DioException(
          requestOptions: response.requestOptions
          ..extra['mapped_error'] = ErrorCodes.tokenInvalidMessage,
        response: response,
          type: DioExceptionType.badResponse,
          error: 'ERR_AUTH_TOKEN_INVALID',
          message: ErrorCodes.tokenInvalidMessage,
        ),
      );
      return;
    }
    handler.next(response);
  }

  @override
  Future<void> onError(DioException err, ErrorInterceptorHandler handler) async {
    final data = err.response?.data;
    final statusCode = err.response?.statusCode;
    if (statusCode == 401 || _isTokenInvalid(data)) {
      await _handleAuthError(data);
      return handler.reject(err);
    }
    handler.next(err);
  }

  bool _isTokenInvalid(dynamic data) {
    if (data is Map<String, dynamic>) {
      final code = data['error_code'] ?? data['errorCode'];
      return ErrorCodes.tokenInvalidCodes.contains(code);
    }
    return false;
  }

  Future<void> _handleAuthError(dynamic data) async {
    if (_isHandlingAuth) return;
    _isHandlingAuth = true;
    try {
      await DataPreference.instance.clearData();
      String? message;
      if (data is Map<String, dynamic>) {
        message = data['error_message']?.toString() ??
            data['errorMessage']?.toString() ??
            data['message']?.toString();
      }
      await AppNavigator.showAuthAlertAndGoLogin(message ?? ErrorCodes.tokenInvalidMessage);
    } finally {
      _isHandlingAuth = false;
    }
  }
}
