import 'dart:convert'; import 'package:http/http.dart' as http; import '../app_config.dart'; import '../models/address_entry.dart'; import '../models/address_record.dart'; import '../models/auth_session.dart'; abstract class AddressRepository { Future saveAddress({ required AuthSession session, required AddressEntry address, }); Future> getMyAddresses({required AuthSession session}); } class HttpAddressRepository implements AddressRepository { const HttpAddressRepository({http.Client? client}) : _client = client; final http.Client? _client; @override Future saveAddress({ required AuthSession session, required AddressEntry address, }) async { final uri = Uri.parse('${AppConfig.apiBaseUrl}/addresses'); late final http.Response response; try { response = await (_client ?? http.Client()).post( uri, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': 'Bearer ${session.token}', }, body: jsonEncode(address.toJson()), ); } catch (_) { throw AddressException( 'No se pudo conectar con el backend en ${AppConfig.apiBaseUrl}.', ); } if (response.statusCode < 200 || response.statusCode >= 300) { final payload = jsonDecode(response.body); final message = payload['message']?.toString() ?? 'Error al guardar la dirección.'; throw AddressException(message); } } @override Future> getMyAddresses({required AuthSession session}) async { final uri = Uri.parse('${AppConfig.apiBaseUrl}/addresses/me'); late final http.Response response; try { response = await (_client ?? http.Client()).get( uri, headers: { 'Accept': 'application/json', 'Authorization': 'Bearer ${session.token}', }, ); } catch (_) { throw AddressException( 'No se pudo conectar con el backend en ${AppConfig.apiBaseUrl}.', ); } if (response.statusCode < 200 || response.statusCode >= 300) { final payload = jsonDecode(response.body); final message = payload['message']?.toString() ?? 'Error al obtener las direcciones.'; throw AddressException(message); } final decoded = jsonDecode(response.body); if (decoded is! List) { return []; } return decoded .whereType>() .map(AddressRecord.fromJson) .toList(growable: false); } } class AddressException implements Exception { AddressException(this.message); final String message; @override String toString() => message; }