import 'package:supabase_flutter/supabase_flutter.dart'; import '../models/service_model.dart'; // Importa gli altri modelli se sono in file separati class ServicesRepository { final _supabase = Supabase.instance.client; // --- RECUPERO TUTTI I SERVIZI --- Future> fetchAllServices() async { try { // La stringa di selezione tira giù il padre e TUTTI i record correlati dalle tabelle figlie final response = await _supabase .from('service') .select(''' *, energy_service(*), fin_service(*), entertainment_service(*) ''') .order('created_at', ascending: false); return (response as List) .map((map) => ServiceModel.fromMap(map)) .toList(); } catch (e) { throw Exception('Errore nel recupero servizi: $e'); } } // --- SALVATAGGIO COMPLETO (A CASCATA) --- Future saveFullService(ServiceModel service) async { try { // 1. Inserimento Padre final serviceData = await _supabase .from('service') .insert(service.toMap()) .select() .single(); final String newId = serviceData['id']; // 2. Inserimento Energy (se presenti) if (service.energyServices.isNotEmpty) { final List> energyToInsert = []; for (var item in service.energyServices) { energyToInsert.add(item.copyWith(serviceId: newId).toMap()); } await _supabase.from('energy_service').insert(energyToInsert); } // 3. Inserimento Finanziamenti (se presenti) if (service.finServices.isNotEmpty) { final List> finToInsert = []; for (var item in service.finServices) { finToInsert.add(item.copyWith(serviceId: newId).toMap()); } await _supabase.from('fin_service').insert(finToInsert); } // 4. Inserimento Entertainment (se presenti) if (service.entertainmentServices.isNotEmpty) { final List> entToInsert = []; for (var item in service.entertainmentServices) { entToInsert.add(item.copyWith(serviceId: newId).toMap()); } await _supabase.from('entertainment_service').insert(entToInsert); } } catch (e) { throw Exception('Errore durante il salvataggio: $e'); } } // --- ELIMINAZIONE --- // Grazie ai "ON DELETE CASCADE" che hai messo nell'SQL, // cancellando il padre Supabase pialla automaticamente i figli. Top! Future deleteService(String id) async { try { await _supabase.from('service').delete().eq('id', id); } catch (e) { throw Exception('Errore durante l\'eliminazione: $e'); } } }