import 'dart:async';

import '../../contracts/error.dart';
import '../../domain/errors.dart';
import '../../domain/ports/script_widget_remote_gateway.dart';
import 'safe_script_http_client.dart';

class ScriptWidgetRemoteClient implements ScriptWidgetRemoteGateway {
  final SafeScriptHttpClient _httpClient;

  ScriptWidgetRemoteClient({SafeScriptHttpClient? httpClient})
    : _httpClient = httpClient ?? SafeScriptHttpClient();

  @override
  Future<String> fetchText(String url) async {
    final uri = Uri.tryParse(url.trim());
    if (uri == null) {
      throw DomainError(ErrorCode.invalidParams, '模块地址必须是有效的 HTTP(S) URL');
    }
    try {
      final response = await _httpClient.request(uri: uri);
      return response.text;
    } on DomainError {
      rethrow;
    } catch (error) {
      final isTimeout = error is TimeoutException;
      throw DomainError(
        isTimeout ? ErrorCode.serverTimeout : ErrorCode.serverUnreachable,
        isTimeout ? '下载模块超时' : '无法下载模块',
        retryable: true,
        details: <String, Object?>{'url': url, 'error': error.toString()},
      );
    }
  }
}
