import 'package:dio/dio.dart';
import 'package:networks_sdk/src/domain/entities/api_request_type.dart';
import 'package:networks_sdk/src/presentation/wiring/api_config.dart';



/// 认证拦截器
/// 自动注入 token 和默认 headers 到每个请求
class AuthInterceptor extends Interceptor {
  final ApiConfig config;

  AuthInterceptor(this.config);

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // 从 options.extra 读取请求元数据
    final requestType =
        options.extra['requestType'] as ApiRequestType? ?? ApiRequestType.request;
    final includeToken = options.extra['includeToken'] as bool? ?? true;
    final customHeaders =
    options.extra['customHeaders'] as Map<String, String>?;

    // 保留重试请求的原始 Request-ID（幂等性）
    // 重试时 options.headers 中已有 app-request-id，
    // 新生成的 headers 会覆盖它导致服务端无法识别为同一请求。
    final existingRequestId = options.headers['app-request-id'] as String?;

    // 构建 headers
    final headers = config.defaultHeaders(
      includeToken: includeToken && requestType != ApiRequestType.login,
      customHeaders: customHeaders,
    );

    // 还原原始 Request-ID
    if (existingRequestId != null) {
      headers['app-request-id'] = existingRequestId;
    }

    options.headers.addAll(headers);
    handler.next(options);
  }
}
