import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:p_tits_pas/models/relais_model.dart'; import 'package:p_tits_pas/services/api/api_config.dart'; import 'package:p_tits_pas/services/api/tokenService.dart'; class RelaisService { static Future> _headers() async { final token = await TokenService.getToken(); return token != null ? ApiConfig.authHeaders(token) : Map.from(ApiConfig.headers); } static String _extractError(String body, String fallback) { try { final decoded = jsonDecode(body); if (decoded is Map) { final message = decoded['message']; if (message is String && message.trim().isNotEmpty) { return message; } } } catch (_) {} return fallback; } static Future> getRelais() async { final response = await http.get( Uri.parse('${ApiConfig.baseUrl}${ApiConfig.relais}'), headers: await _headers(), ); if (response.statusCode != 200) { throw Exception( _extractError(response.body, 'Erreur chargement relais'), ); } final List data = jsonDecode(response.body); return data .whereType>() .map(RelaisModel.fromJson) .toList(); } static Future createRelais(Map payload) async { final response = await http.post( Uri.parse('${ApiConfig.baseUrl}${ApiConfig.relais}'), headers: await _headers(), body: jsonEncode(payload), ); if (response.statusCode != 201 && response.statusCode != 200) { throw Exception( _extractError(response.body, 'Erreur création relais'), ); } return RelaisModel.fromJson( jsonDecode(response.body) as Map); } static Future updateRelais( String id, Map payload, ) async { final response = await http.patch( Uri.parse('${ApiConfig.baseUrl}${ApiConfig.relais}/$id'), headers: await _headers(), body: jsonEncode(payload), ); if (response.statusCode != 200) { throw Exception( _extractError(response.body, 'Erreur mise à jour relais'), ); } return RelaisModel.fromJson( jsonDecode(response.body) as Map); } static Future deleteRelais(String id) async { final response = await http.delete( Uri.parse('${ApiConfig.baseUrl}${ApiConfig.relais}/$id'), headers: await _headers(), ); if (response.statusCode != 200 && response.statusCode != 204) { throw Exception( _extractError(response.body, 'Erreur suppression relais'), ); } } }