import 'package:dio/dio.dart';

import '../../feature/common/data/models/error_model.dart';

class ErrorHandlerInterceptors extends Interceptor {
  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (err.response != null && err.response!.statusCode != null) {
      if (err.response?.data is String) {
        final errorMessage = err.response?.data as String?;
        final error = ErrorModel(
          detail: errorMessage?.replaceAll(RegExp(r'<[^>]+>'), '') ?? '',
        );
        handler.next(
          DioException(
            requestOptions: err.requestOptions,
            response: Response(
              requestOptions: err.requestOptions,
              data: error.toJson(),
            ),
          ),
        );
        return;
      } else {
        handler.next(err);
        return;
      }
    }
    const error = ErrorModel(detail: "");
    handler.next(
      DioException(
        requestOptions: err.requestOptions,
        response: Response(
          requestOptions: err.requestOptions,
          data: error.toJson(),
        ),
      ),
    );
    return;
  }
}
