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

class RequestInterceptor extends Interceptor {
  final StorageService _storageService;

  RequestInterceptor(this._storageService);

  @override
  Future<void> onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    final uuid = _generateUuid();
    options.extra['uuid'] = uuid;

    final Map<String, dynamic> headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'X-Request-UUID': uuid,
      'X-Timestamp': DateTime.now().millisecondsSinceEpoch.toString(),
    };

    final token = await _storageService.getToken();
    if (token != null && token.isNotEmpty) {
      headers['Authorization'] = 'Bearer $token';
      final clientId = await _storageService.getClientId();
      if (clientId != null && clientId.isNotEmpty) {
        headers['clientid'] = clientId;
      }
    }

    options.headers.addAll(headers);

    _printRequestLog(options, uuid);

    handler.next(options);
  }

  String _generateUuid() {
    return '${DateTime.now().millisecondsSinceEpoch}_${_randomString(8)}';
  }

  String _randomString(int length) {
    const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    return List.generate(length, (index) => chars[index % chars.length]).join();
  }

  void _printRequestLog(RequestOptions options, String uuid) {
    Log.info('********************** Request START **********************');
    Log.info('UUID: $uuid');
    Log.info('Method: ${options.method}  URL: ${options.uri}');
    // Log.info('URL: ${options.uri}');
    Log.info('Headers: ${options.headers}');
    if (options.data != null) {
      Log.info('POST入参: ${options.data}');
    }
    if (options.queryParameters.isNotEmpty) {
      Log.info('URL入参: ${options.queryParameters}');
    }
    Log.info('********************** Request END **********************');
  }
}
