import 'package:dio/dio.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';
    }

    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) {
    print('========== Request START ==========');
    print('UUID: $uuid');
    print('Method: ${options.method}');
    print('URL: ${options.uri}');
    print('Headers: ${options.headers}');
    if (options.data != null) {
      print('Data: ${options.data}');
    }
    if (options.queryParameters.isNotEmpty) {
      print('Params: ${options.queryParameters}');
    }
    print('========== Request END ==========');
  }
}