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

class LoggerInterceptor extends Interceptor {
  final Logger _logger = Logger(
    printer: PrettyPrinter(
      methodCount: 0,
      lineLength: 120,
      printTime: true,
      colors: true,
    ),
  );

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    final uri = options.uri;
    _logger.i(
      '🚀 ${options.method} $uri\n'
          'Headers: ${_formatHeaders(options.headers)}\n'
          'Query: ${options.queryParameters}\n'
          'Body: ${_formatData(options.data)}',
    );
    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    final uri = response.requestOptions.uri;
    final statusCode = response.statusCode;
    _logger.d(
      '✅ $statusCode ${response.requestOptions.method} $uri\n'
          'Response: ${_formatData(response.data)}',
    );
    handler.next(response);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    final uri = err.requestOptions.uri;
    final statusCode = err.response?.statusCode ?? 'Unknown';
    _logger.e(
      '❌ $statusCode ${err.requestOptions.method} $uri\n'
          'Error: ${err.message}\n'
          'Response: ${_formatData(err.response?.data)}',
    );
    handler.next(err);
  }

  String _formatHeaders(Map<String, dynamic> headers) {
    final filtered = Map<String, dynamic>.from(headers);
    // Hide sensitive headers
    if (filtered.containsKey('Authorization')) {
      filtered['Authorization'] = '***';
    }
    return filtered.toString();
  }

  String _formatData(dynamic data) {
    if (data == null) return 'null';
    if (data is String && data.length > 1000) {
      return '${data.substring(0, 1000)}... (truncated)';
    }
    return data.toString();
  }
}