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';
import '../../services/device_info.dart';
import '../../services/package_info.dart';
import '../../../app/config/api_paths.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);

    await _applyDeleteAccountHeadersIfNeeded(options);

    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');
    }
  }

  Future<void> _applyDeleteAccountHeadersIfNeeded(RequestOptions options) async {
    if (!options.path.contains(APIPaths.verifyDeleteAccount)) return;
    try {
      final deviceKey = await DeviceInfo.getDeviceId();
      final details = await DeviceInfo.getDetails();
      final version = await AppInfoHelper.version;
      options.headers.addAll({
        'device-key': deviceKey,
        'operating-system': details.operatingSystem ?? 'Unknown',
        'device-name': details.userDeviceName ?? 'Unknown',
        'version': version,
        'requestId': const Uuid().v4(),
        'lang': 'vi',
      });
    } catch (e) {
      debugPrint('⚠️ RequestInterceptor: failed to add delete headers - $e');
    }
  }
}
