import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:intl/intl.dart'; class OpenExchangeService { OpenExchangeService({required this.httpClient, required this.apiKey}); final http.Client httpClient; final String apiKey; Future fetchUsdToSekRate({required DateTime estDate}) async { if (apiKey == 'REPLACE_WITH_YOUR_OPENEXCHANGE_API_KEY') { throw StateError('OpenExchange API key is not configured.'); } final date = DateFormat('yyyy-MM-dd').format(estDate); final uri = Uri.https( 'openexchangerates.org', '/api/historical/$date.json', {'app_id': apiKey, 'symbols': 'SEK'}, ); final response = await httpClient.get(uri); if (response.statusCode != 200) { throw StateError('OpenExchange request failed (${response.statusCode}).'); } final json = jsonDecode(response.body) as Map; final rates = json['rates'] as Map?; final sek = rates?['SEK']; if (sek == null) { throw StateError('SEK rate was missing in API response.'); } return (sek as num).toDouble(); } }