import 'package:dio/dio.dart';
import 'package:networks_sdk/src/data/datasources/http/api_client.dart';
import 'package:networks_sdk/src/data/dto/api_requestable.dart';
import 'package:networks_sdk/src/domain/entities/api_error.dart';
import 'package:networks_sdk/src/domain/entities/api_request_type.dart';
import 'package:networks_sdk/src/presentation/wiring/api_config.dart';
import '../../../networks_sdk_platform_interface.dart';
import '../../domain/entities/http_method.dart';

class NetworksSdkMethodChannelDataSource 
{
  final NetworksSdkPlatform platform;

  late ApiClient apiClient;

  NetworksSdkMethodChannelDataSource(this.platform);

  Future<String?> getPlatformVersion() async {
    return await getPlatformVersion();
  }

  void initialize(ApiConfig apiConfig){
    apiClient = ApiClient(config: apiConfig);
  }

  /// 执行 API 请求 — 唯一入口
  ///
  /// 流程：网络前置检查 → 构建 URL → 设置元数据 → 执行请求 → 解码响应 → 错误映射
  /// 拦截器负责：header 注入、Token 刷新重试、日志
  ///
  /// Upload 类型支持两种模式：
  /// - 自有后端上传：path 为相对路径，自动拼接 baseURL
  /// - S3 presigned URL：path 以 http 开头，直接使用全路径
  Future<T?> executeRequest<T>(ApiRequestable<T> request) async {
    // 前置检查：网络不可用时直接抛错，避免无效请求
    if (apiClient.config.onCheckNetworkAvailable != null) {
      final available = await apiClient.config.onCheckNetworkAvailable!();
      if (!available) {
        apiClient.config.onLog?.call(
          'Network unavailable, abort request: ${request.path}',
          tag: 'ApiClient',
        );
        throw const ApiError.noNetworkConnection();
      }
    }

    try {
      // Upload 且 path 以 http 开头 → 直接用全路径（S3 presigned URL）
      // 否则 → 拼接 baseURL
      final isUpload = request.requestType == ApiRequestType.upload;
      final path = request.path;
      final url = (isUpload && path.startsWith('http')) ? path : '${apiClient.config.baseURL}$path';

      // 将请求元数据写入 extra，供拦截器读取
      final options = Options(
        method: request.method.value,
        extra: {
          'requestType': request.requestType,
          'includeToken': request.includeToken,
          'customHeaders': request.customHeaders,
        },
      );

      // 访问 parameters 触发代码生成器的 fromJson 注册
      // （@ApiRequest 生成的 mixin 在 parameters getter 中注册响应类型）
      final params = request.parameters;

      // GET → queryParameters；POST/PUT/DELETE/PATCH → JSON body；Upload → uploadData
      final isGet = request.method == HttpMethod.get;
      final response = await apiClient.dio.request(
        url,
        data: isUpload ? request.uploadData : (isGet ? null : params),
        queryParameters: isGet ? params : null,
        options: options,
      );

      // 解码响应（Upload 类型通常需要 override decodeResponse）
      return request.decodeResponse(response);
    } on DioException catch (e) {
      throw apiClient.mapDioError(e);
    } on ApiError {
      rethrow;
    } catch (e) {
      throw ApiError.unknown(e.toString());
    }
  }

}
