import 'package:equatable/equatable.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flux/core/data/core_repository.dart'; import 'package:flux/features/company/models/company_model.dart'; import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; import 'package:flux/features/master_data/store/models/store_model.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:collection/collection.dart'; // Per firstWhereOrNull // Importa lo state con l'Enum e il CoreRepository... part 'session_state.dart'; class SessionCubit extends Cubit { final CoreRepository _repository; final SharedPreferences _prefs; // Iniettato via GetIt final SupabaseClient _supabase = Supabase.instance.client; static const String _lastStoreKey = 'last_selected_store_id'; SessionCubit(this._repository, this._prefs) : super(const SessionState(status: SessionStatus.initial)) { initializeSession(); // Possiamo metterci in ascolto dei cambiamenti di Auth (Login/Logout) _supabase.auth.onAuthStateChange.listen((data) { final AuthChangeEvent event = data.event; if (event == AuthChangeEvent.signedIn) { initializeSession(); } else if (event == AuthChangeEvent.signedOut) { emit(const SessionState(status: SessionStatus.unauthenticated)); } }); } Future initializeSession() async { final user = _supabase.auth.currentUser; if (user == null) { return emit(state.copyWith(status: SessionStatus.unauthenticated)); } try { // 1. Controllo Azienda final company = await _repository.getCompanyByOwnerId(user.id); if (company == null) { return emit( state.copyWith( status: SessionStatus.onboardingRequired, user: user, onboardingStep: OnboardingStep.company, ), ); } else { emit(state.copyWith(company: company)); } // 2. Controllo Negozi final stores = await _repository.getStoresByCompanyId(company.id!); if (stores.isEmpty) { return emit( state.copyWith( status: SessionStatus.onboardingRequired, user: user, company: company, onboardingStep: OnboardingStep.store, ), ); } else { emit(state.copyWith(currentStore: stores.first)); } // 3. Controllo Staff (Paziente Zero) final staff = await _repository.getStaffMemberByUserId(user.id); if (staff == null) { return emit( state.copyWith( status: SessionStatus.onboardingRequired, user: user, company: company, onboardingStep: OnboardingStep.staff, ), ); } // --- TUTTO COMPLETATO: LOGICA DEL NEGOZIO DI DEFAULT --- // Leggiamo l'ultimo negozio dalle SharedPreferences final lastStoreId = _prefs.getString(_lastStoreKey); // Cerchiamo quel negozio nella lista. Se non c'è (magari è stato eliminato), prendiamo il primo. final activeStore = stores.firstWhereOrNull((s) => s.id == lastStoreId) ?? stores.first; // Se non avevamo il lastStoreId salvato, salviamolo ora if (lastStoreId != activeStore.id && activeStore.id != null) { await _prefs.setString(_lastStoreKey, activeStore.id!); } // 4. BENVENUTO A BORDO emit( state.copyWith( status: SessionStatus.authenticated, user: user, company: company, currentStore: activeStore, currentStaff: staff, onboardingStep: OnboardingStep.none, // Svuotiamo l'onboarding ), ); } catch (e) { // Se esplode il database, non lasciamo l'app freezata in 'initial' emit( state.copyWith( status: SessionStatus .unauthenticated, // O un nuovo stato SessionStatus.error ), ); } } // --- FUNZIONE EXTRA: CAMBIO NEGOZIO DALLA DASHBOARD --- Future changeStore(StoreModel newStore) async { if (newStore.id != null) { await _prefs.setString(_lastStoreKey, newStore.id!); emit(state.copyWith(currentStore: newStore)); } } // --- LOGOUT --- Future signOut() async { await _supabase.auth.signOut(); // Non serve emettere stato qui, ci pensa il listener nel costruttore! } void setIsMobileDevice(bool isMobile) { emit(state.copyWith(isMobileDevice: isMobile)); } }