import 'dart:convert';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:mypoint_flutter_app/shared/preferences/data_preference.dart';
import 'package:uuid/uuid.dart';

class RequestInterceptor extends Interceptor {
  @override
  Future<void> onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    String authKey = 'Authorization';
    String? token = DataPreference.instance.token;
    if (token!= null) {
      options.headers[authKey] = "Bearer $token";
    }
    
    // Base headers for all platforms
    Map<String, dynamic> headers = {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Accept-Language': 'vi',
    };
    
    // Only add X-Request-Id for non-web platforms to avoid CORS issues
    if (!kIsWeb) {
      headers['X-Request-Id'] = Uuid().v4();
    }
    
    options.headers.addAll(headers);

    if (kIsWeb) {
      _normalizeWebBody(options);
    }
    handler.next(options);
  }

  void _normalizeWebBody(RequestOptions options) {
    final body = options.data;
    if (body == null) return;

    final contentType = (options.headers[Headers.contentTypeHeader] ?? options.contentType ?? '')
        .toString()
        .toLowerCase();
    if (!contentType.contains('application/json')) {
      return;
    }

    try {
      if (body is Uint8List) {
        options.data = utf8.decode(body);
        return;
      }
      if (body is ByteBuffer) {
        options.data = utf8.decode(body.asUint8List());
        return;
      }
      if (body is ByteData) {
        options.data = utf8.decode(body.buffer.asUint8List());
        return;
      }
      if (body is List<int>) {
        options.data = utf8.decode(body);
        return;
      }
      if (body is Map || body is List) {
        options.data = jsonEncode(body);
        return;
      }
      if (body is String) {
        return;
      }
      options.data = jsonEncode(body);
    } catch (e) {
      debugPrint('⚠️ RequestInterceptor: failed to normalize JSON body - $e');
    }
  }
}
