import 'package:dio/dio.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../../core/api/api_client.dart'; import '../../../core/api/api_endpoints.dart'; import '../../../core/api/api_response.dart'; import '../../../core/auth/auth_provider.dart'; import '../domain/booking.dart'; /// Dépôt de données pour les réservations. class BookingRepository { BookingRepository(this._apiClient); final ApiClient _apiClient; Future> fetchBookings() async { final response = await _apiClient.get(ApiEndpoints.bookings); final list = ApiResponse.list(response.data, 'bookings'); return list.map((json) => Booking.fromJson(json as Map)).toList(); } Future fetchBooking(String uuid) async { final response = await _apiClient.get(ApiEndpoints.booking(uuid)); final json = ApiResponse.object(response.data, 'booking'); return Booking.fromJson(json); } Future createBooking({ required String machineUuid, required DateTime slotStart, required DateTime slotEnd, }) async { try { final response = await _apiClient.post( ApiEndpoints.bookings, data: { 'machine_uuid': machineUuid, 'slot_start': slotStart.toUtc().toIso8601String(), 'slot_end': slotEnd.toUtc().toIso8601String(), }, ); final json = ApiResponse.object(response.data, 'booking'); return Booking.fromJson(json); } on DioException catch (error) { throw BookingException(ApiResponse.errorMessage(error, fallback: 'Impossible de réserver')); } } Future cancelBooking(String uuid) async { try { final response = await _apiClient.patch(ApiEndpoints.bookingCancel(uuid)); final json = ApiResponse.object(response.data, 'booking'); return Booking.fromJson(json); } on DioException catch (error) { throw BookingException(ApiResponse.errorMessage(error, fallback: 'Impossible d\'annuler')); } } Future moveBooking({ required String uuid, required DateTime slotStart, required DateTime slotEnd, }) async { try { final response = await _apiClient.patch( ApiEndpoints.bookingMove(uuid), data: { 'slot_start': slotStart.toUtc().toIso8601String(), 'slot_end': slotEnd.toUtc().toIso8601String(), }, ); final json = ApiResponse.object(response.data, 'booking'); return Booking.fromJson(json); } on DioException catch (error) { throw BookingException(ApiResponse.errorMessage(error, fallback: 'Impossible de modifier')); } } } class BookingException implements Exception { BookingException(this.message); final String message; @override String toString() => message; } final bookingRepositoryProvider = Provider((ref) { return BookingRepository(ref.watch(apiClientProvider)); }); final bookingsProvider = FutureProvider>((ref) async { final token = ref.watch(authProvider.select((state) => state.accessToken)); if (token == null || token.isEmpty) { throw StateError('Non authentifié'); } return ref.watch(bookingRepositoryProvider).fetchBookings(); }); final bookingDetailProvider = FutureProvider.family((ref, uuid) async { return ref.watch(bookingRepositoryProvider).fetchBooking(uuid); });