import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'package:flux/core/blocs/session/session_cubit.dart'; import 'package:flux/core/utils/extensions.dart'; import 'package:flux/features/attachments/models/attachment_model.dart'; import 'package:flux/features/customers/data/customer_repository.dart'; import 'package:flux/features/customers/models/customer_file_model.dart'; import 'package:flux/features/operations/models/operation_file_model.dart'; import 'package:get_it/get_it.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; import '../models/operation_model.dart'; class OperationsRepository { final _supabase = Supabase.instance.client; final companyId = GetIt.I.get().state.company!.id; final CustomerRepository _customerRepository = GetIt.I(); // --- RECUPERO SINGOLO SERVIZIO CON JOIN COMPLETO --- Future fetchOperationById(String id) async { try { final response = await _supabase .from('operation') .select(''' *, customer(name), staff_member(name) ''') .eq('id', id) .single(); return OperationModel.fromMap(response); } catch (e) { throw Exception('Errore nel caricamento del servizio: $e'); } } // --- RECUPERO PAGINATO CON FILTRI E JOIN --- Future> fetchOperations({ required String companyId, required int offset, int limit = 50, String? searchTerm, DateTimeRange? dateRange, }) async { try { var query = _supabase .from('operation') .select(''' *, customer(name), staff_member(name), attachments(*) ''') .eq('company_id', companyId); // Filtro Range Date if (dateRange != null) { query = query .gte('created_at', dateRange.start.toIso8601String()) .lte('created_at', dateRange.end.toIso8601String()); } if (searchTerm != null && searchTerm.isNotEmpty) { // Filtra sui campi della tabella principale O su quelli della tabella joinata query = query.or( 'reference.ilike.%$searchTerm%,note.ilike.%$searchTerm%,customer.name.ilike.%$searchTerm%', ); } final response = await query .order('created_at', ascending: false) .range(offset, offset + limit - 1); return (response as List) .map((map) => OperationModel.fromMap(map)) .toList(); } catch (e) { throw Exception('$e'); } } Stream> getLastStoreOperationsStream({ required String storeId, required int limit, }) { return _supabase .from('operation') .stream(primaryKey: ['id']) .eq('store_id', storeId) .order('created_at', ascending: false) .limit(limit) .map( (listOfMaps) => listOfMaps.map((map) => OperationModel.fromMap(map)).toList(), ); } // --- SALVATAGGIO COMPLETO (PRIMA PADRE, POI FIGLI) --- Future saveFullOperation(OperationModel operation) async { try { // 1. Upsert del record principale final operationData = await _supabase .from('operation') .upsert(operation.toMap()) .select() .single(); final String newId = operationData['id']; // 4. UPLOAD DEI FILE LOCALI (Nuovi) // Filtriamo solo i file che non hanno ancora un ID (quindi sono locali) final localFilesToUpload = operation.attachments .where((f) => f.id == null) .toList(); if (localFilesToUpload.isNotEmpty) { final List uploadTasks = []; for (var file in localFilesToUpload) { final storagePath = '$companyId/operations/$newId/${DateTime.now().millisecondsSinceEpoch}_${file.name}.${file.extension}'; final String mimeType = file.extension.toLowerCase() == 'pdf' ? 'application/pdf' : 'image/${file.extension}'; final fileToSave = file.copyWith( operationId: newId, storagePath: storagePath, ); // Creiamo una funzione asincrona per caricare file e scrivere nel DB Future uploadAndLink() async { // A. Upload nel Bucket Storage (usiamo i bytes così funziona anche su Web!) await _supabase.storage .from('documents') .uploadBinary( storagePath, fileToSave.localBytes!, fileOptions: FileOptions(contentType: mimeType, upsert: true), ); // B. Inserimento riga nel DB relazionale await _supabase.from('attachment').insert(fileToSave.toMap()); } uploadTasks.add(uploadAndLink()); } // Eseguiamo tutti gli upload in parallelo per la massima velocità await Future.wait(uploadTasks); } // 5. GRAN FINALE: RECUPERO DEL MODELLO COMPLETO E AGGIORNATO // Interroghiamo Supabase per farci restituire la pratica con TUTTI gli ID generati // (inclusi quelli della tabella operation_file appena inseriti) final updatedOperationData = await _supabase .from('operation') .select(''' *, staff_member(name), customer(name), attachments(*) ''') .eq('id', newId) .single(); return OperationModel.fromMap(updatedOperationData); } catch (e) { // Qui potresti aggiungere una logica di "rollback manuale" se necessario throw Exception('$e'); } } // --- ELIMINAZIONE --- Future deleteOperation(String id) async { try { await _supabase.from('operation').delete().eq('id', id); } catch (e) { throw Exception('$e'); } } // --- RECUPERO TIPI CONTENUTI PIÙ FREQUENTI PER AUTOCOMPLETE --- Future> fetchTopEntertainmentTypes(String companyId) async { try { // Cerchiamo i tipi più frequenti associati ai servizi di questa company // Nota: dobbiamo passare attraverso la tabella 'operation' per filtrare per company_id final response = await _supabase .from('operation') .select('description') .eq('company_id', companyId) .eq('type', 'Entertainment') .limit(50); // Prendiamo un campione // Logica rapida per contare le occorrenze e prendere i primi 5 final Map counts = {}; for (var item in (response as List)) { final description = item['description'] as String; counts[description] = (counts[description] ?? 0) + 1; } var sortedKeys = counts.keys.toList() ..sort((a, b) => counts[b]!.compareTo(counts[a]!)); return sortedKeys.take(5).toList(); } catch (e) { return [ "Netflix", "DAZN", "Disney+", "Sky", ]; // Fallback se non c'è ancora storia } } /// Ascolta in tempo reale i file caricati per una pratica Stream> getOperationFilesStream(String operationId) { return _supabase .from('attachment') .stream(primaryKey: ['id']) .eq('operation_id', operationId) .order('created_at', ascending: false) .map( (listOfMaps) => listOfMaps.map((map) => AttachmentModel.fromMap(map)).toList(), ); } Future uploadAndRegisterOperationFile({ required String operationId, required PlatformFile pickedFile, }) async { final cleanFileName = pickedFile.name.replaceAll( RegExp(r'[^a-zA-Z0-9\.\-]'), '_', ); final storagePath = '$companyId/operations/$operationId/${DateTime.now().millisecondsSinceEpoch}_$cleanFileName'; final int fileSize = pickedFile.size; final fileToSave = AttachmentModel( companyId: GetIt.I.get().state.company!.id!, operationId: operationId, name: cleanFileName.fileNameWithoutExtension(), extension: cleanFileName.fileExtension(), storagePath: storagePath, fileSize: fileSize, ); final String mimeType = fileToSave.extension.toLowerCase() == 'pdf' ? 'application/pdf' : 'image/${fileToSave.extension}'; try { // Usiamo bytes invece del path per massima compatibilità if (pickedFile.bytes == null && pickedFile.path == null) { throw 'Impossibile leggere il contenuto del file'; } // Se siamo su desktop/mobile abbiamo il path, su web abbiamo i bytes if (pickedFile.bytes != null) { await _supabase.storage .from('documents') .uploadBinary( storagePath, pickedFile.bytes!, fileOptions: FileOptions(contentType: mimeType, upsert: true), ); } final response = await _supabase .from('attachment') .insert(fileToSave.toMap()) .select() .single(); return AttachmentModel.fromMap(response); } catch (e) { throw 'Errore durante l\'upload: $e'; } } Future copyFileToCustomer({ required OperationFileModel file, required String customerId, }) async { await _supabase .from('attachment') .update({'customer_id': customerId}) .eq('id', file.id!); } Future deleteOperationFiles(List files) async { if (files.isEmpty) return; // 1. Prepariamo le liste di ID e di Percorsi final List idsToDelete = files.map((f) => f.id!).toList(); final List storagePaths = files.map((f) => f.storagePath).toList(); try { await _supabase .from('attachment') .update({'operation_id': null}) .inFilter('id', idsToDelete); await _supabase.storage.from('documents').remove(storagePaths); } on PostgrestException catch (e) { throw 'Errore database: ${e.message}'; } catch (e) { throw 'Errore durante l\'eliminazione dei file: $e'; } } }