import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import '../../utils/app_logger.dart';

/// 로깅 인터셉터
///
/// 네트워크 요청과 응답을 로그로 기록합니다.
/// 디버그 모드에서만 활성화됩니다.
class LoggingInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (kDebugMode) {
      final uri = options.uri;
      final method = options.method;
      final headers = options.headers;

      AppLogger.debug(
        '═══════════════════════════════════════════════════════════════',
      );
      AppLogger.debug('>>> REQUEST [$method] $uri');
      AppLogger.debug('>>> Headers: $headers');

      if (options.data != null) {
        AppLogger.debug('>>> Body: ${options.data}');
      }

      if (options.queryParameters.isNotEmpty) {
        AppLogger.debug('>>> Query Parameters: ${options.queryParameters}');
      }
    }

    return handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (kDebugMode) {
      final statusCode = response.statusCode;
      final uri = response.requestOptions.uri;

      AppLogger.debug('<<< RESPONSE [$statusCode] $uri');

      if (response.headers.map.isNotEmpty) {
        AppLogger.debug('<<< Headers: ${response.headers.map}');
      }

      // 응답 본문은 너무 길 수 있으므로 처음 500자만 출력
      final responseData = response.data.toString();
      if (responseData.length > 500) {
        AppLogger.debug(
          '<<< Body: ${responseData.substring(0, 500)}...(truncated)',
        );
      } else {
        AppLogger.debug('<<< Body: $responseData');
      }

      AppLogger.debug(
        '═══════════════════════════════════════════════════════════════',
      );
    }

    return handler.next(response);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (kDebugMode) {
      final uri = err.requestOptions.uri;
      final message = err.message;

      AppLogger.debug(
        '═══════════════════════════════════════════════════════════════',
      );
      AppLogger.debug('!!! ERROR $uri');
      AppLogger.debug('!!! Message: $message');

      if (err.response != null) {
        AppLogger.debug('!!! Status Code: ${err.response!.statusCode}');
        AppLogger.debug('!!! Response: ${err.response!.data}');
      }

      AppLogger.debug('!!! Error Type: ${err.type}');
      AppLogger.debug(
        '═══════════════════════════════════════════════════════════════',
      );
    }

    return handler.next(err);
  }
}
