import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import '../auth/auth_store.dart';
import '../auth/csrf_token.dart';
import '../auth/http_client.dart';
class ReportDeliveryException implements Exception {
const ReportDeliveryException(this.message);
final String message;
}
class ReportDeliveryClient {
ReportDeliveryClient({http.Client? client, String? baseUrl})
: _client = client ?? createPlatformClient(),
_baseUrl =
(baseUrl ??
const String.fromEnvironment(
'MACHWEIS_API_BASE_URL',
defaultValue: 'https://[PRIVATE_API_HOST]',
))
.replaceFirst(RegExp(r'/$'), '');
final http.Client _client;
final String _baseUrl;
Future<void> send(String reportId) async {
Future<http.Response> request(bool refresh) async {
final headers = <String, String>{'Content-Type': 'application/json'};
if (kIsWeb) {
final csrf = readCsrfToken();
if (csrf != null) headers['X-CSRF-Token'] = csrf;
} else {
headers['Authorization'] =
'Bearer ${await AuthStore.instance.accessToken(forceRefresh: refresh)}';
}
return _client
.post(
Uri.parse('$_baseUrl/[INTERNAL_REPORT_DELIVERY_ENDPOINT]'),
headers: headers,
)
.timeout(const Duration(seconds: 20));
}
try {
var response = await request(false);
if (response.statusCode == 401) response = await request(true);
if (response.statusCode == 202) return;
if (response.statusCode == 422) {
throw const ReportDeliveryException(
'Der Bericht ist nicht final oder beim Kunden fehlt eine E-Mail-Adresse.',
);
}
throw const ReportDeliveryException(
'Der Versand konnte nicht gestartet werden.',
);
} on TimeoutException {
throw const ReportDeliveryException('Der Versandserver antwortet nicht.');
} on http.ClientException {
throw const ReportDeliveryException(
'Offline – bitte später erneut versuchen.',
);
}
}
}
