import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:networks_sdk/src/presentation/wiring/network_callbacks.dart';

/// 日志拦截器
/// 统一打印请求 + 响应（一个日志块）
class LoggingInterceptor extends Interceptor {
  final OnLog? onLog;
  final bool enabled;

  LoggingInterceptor({this.onLog, this.enabled = true});

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (enabled && onLog != null) {
      _logRequestAndResponse(response);
    }
    handler.next(response);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (enabled && onLog != null) {
      _logError(err);
    }
    handler.next(err);
  }

  void _logRequestAndResponse(Response response) {
    try {
      final logData = {
        'url': response.requestOptions.uri.toString(),
        'method': response.requestOptions.method,
        'request': {
          if (response.requestOptions.data != null)
            'body': response.requestOptions.data,
        },
        'response': {
          'status': response.statusCode,
          if (response.data != null) 'body': response.data,
        },
      };

      const encoder = JsonEncoder.withIndent('  ');
      onLog!(
        'API Request + Response:\n${encoder.convert(logData)}',
        tag: 'Network',
      );
    } catch (e) {
      onLog!(
        'API: ${response.requestOptions.uri} -> ${response.statusCode}',
        tag: 'Network',
      );
    }
  }

  void _logError(DioException error) {
    try {
      final logData = {
        'url': error.requestOptions.uri.toString(),
        'method': error.requestOptions.method,
        'type': error.type.toString(),
        'message': error.message,
        if (error.response != null) ...{
          'status': error.response!.statusCode,
          'data': error.response!.data,
        },
      };

      const encoder = JsonEncoder.withIndent('  ');
      onLog!(
        'API Error:\n${encoder.convert(logData)}',
        tag: 'Network',
      );
    } catch (e) {
      onLog!('API Error: ${error.message}', tag: 'Network');
    }
  }
}
