import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import '../services/error_logger.dart';

/// Interceptor that logs all failed requests to [ErrorLogger] for
/// structured diagnostics and future Sentry/Crashlytics integration.
class ErrorLogInterceptor extends Interceptor {
  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    final entry = {
      'timestamp': DateTime.now().toIso8601String(),
      'method': err.requestOptions.method,
      'url': err.requestOptions.uri.toString(),
      'statusCode': err.response?.statusCode,
      'errorType': err.type.name,
      'message': err.message ?? err.error?.toString() ?? 'unknown',
      'retryCount': err.requestOptions.extra['_retryCount'] ?? 0,
    };

    ErrorLogger.instance.log(entry);

    if (kDebugMode) {
      debugPrint('[API Error] ${entry['method']} ${entry['url']} '
          '→ ${entry['statusCode'] ?? entry['errorType']} '
          '(retries: ${entry['retryCount']})');
    }

    handler.next(err);
  }
}
