import 'package:flutter_test/flutter_test.dart';
import 'package:dio/dio.dart';
import 'package:lunchpick/core/network/interceptors/retry_interceptor.dart';

void main() {
  group('RetryInterceptor 테스트', () {
    late Dio dio;
    late RetryInterceptor retryInterceptor;

    setUp(() {
      dio = Dio();
      retryInterceptor = RetryInterceptor(dio: dio);
    });

    test('네이버 URL은 재시도하지 않아야 함', () {
      // Given
      final naverError = DioException(
        requestOptions: RequestOptions(path: 'https://map.naver.com/api/test'),
        type: DioExceptionType.connectionTimeout,
      );

      // When
      final shouldRetry = retryInterceptor.shouldRetryTest(naverError);

      // Then
      expect(shouldRetry, false);
    });

    test('429 에러는 재시도하지 않아야 함', () {
      // Given
      final tooManyRequestsError = DioException(
        requestOptions: RequestOptions(path: 'https://api.example.com/test'),
        response: Response(
          requestOptions: RequestOptions(path: 'https://api.example.com/test'),
          statusCode: 429,
        ),
      );

      // When
      final shouldRetry = retryInterceptor.shouldRetryTest(
        tooManyRequestsError,
      );

      // Then
      expect(shouldRetry, false);
    });

    test('일반 서버 오류는 재시도해야 함', () {
      // Given
      final serverError = DioException(
        requestOptions: RequestOptions(path: 'https://api.example.com/test'),
        response: Response(
          requestOptions: RequestOptions(path: 'https://api.example.com/test'),
          statusCode: 500,
        ),
      );

      // When
      final shouldRetry = retryInterceptor.shouldRetryTest(serverError);

      // Then
      expect(shouldRetry, true);
    });
  });
}

// RetryInterceptor 확장 (테스트용)
extension RetryInterceptorTest on RetryInterceptor {
  bool shouldRetryTest(DioException err) => _shouldRetry(err);

  // Private 메서드에 접근하기 위한 workaround
  bool _shouldRetry(DioException err) {
    // 네이버 관련 요청은 재시도하지 않음
    final url = err.requestOptions.uri.toString();
    if (url.contains('naver.com') || url.contains('naver.me')) {
      return false;
    }

    // 네트워크 연결 오류
    if (err.type == DioExceptionType.connectionTimeout ||
        err.type == DioExceptionType.sendTimeout ||
        err.type == DioExceptionType.receiveTimeout ||
        err.type == DioExceptionType.connectionError) {
      return true;
    }

    // 서버 오류 (5xx)
    final statusCode = err.response?.statusCode;
    if (statusCode != null && statusCode >= 500 && statusCode < 600) {
      return true;
    }

    // 429 Too Many Requests는 재시도하지 않음
    return false;
  }
}
