import 'dart:developer';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:dio_smart_retry/dio_smart_retry.dart';

RetryInterceptor buildRetryInterceptor(Dio dio) {
  return RetryInterceptor(
    dio: dio,
    retryDelays: const [
      Duration(milliseconds: 600),
      Duration(seconds: 1),
      Duration(seconds: 2),
    ],
    logPrint: (o) => log(o, name: 'DIO_RETRY'),
    retryEvaluator: (e, _) {
      final code = e.response?.statusCode ?? 0;

      final serverTransient = code == 502 || code == 503 || code == 504;
      final connectionIssue =
          e.type == DioExceptionType.connectionTimeout ||
          e.type == DioExceptionType.receiveTimeout ||
          e.type == DioExceptionType.sendTimeout ||
          e.type == DioExceptionType.connectionError ||
          (e.type == DioExceptionType.unknown && e.error is SocketException);

      return serverTransient || connectionIssue;
    },
  );
}
