import 'package:flutter/foundation.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/company/models/company_model.dart';
import 'package:flux/features/master_data/store/models/store_model.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:get_it/get_it.dart';
// Importa i tuoi modelli...
import 'package:supabase_flutter/supabase_flutter.dart';

class CoreRepository {
  final _supabase = Supabase.instance.client;

  // --- QUERY DI SESSIONE (Uso di maybeSingle per evitare crash) ---

  Future<CompanyModel?> getCompanyByOwnerId(String userId) async {
    try {
      final response = await _supabase
          .from(Tables.companies)
          .select()
          .eq('user_id', userId) // <-- Assicurati di avere questo campo nel DB!
          .maybeSingle();

      if (response == null) return null;
      return CompanyModel.fromMap(response);
    } catch (e) {
      debugPrint('Errore recupero azienda: $e');
      throw Exception('$e');
    }
  }

  Future<CompanyModel?> getCompanyById(String companyId) async {
    try {
      final response = await _supabase
          .from(Tables.companies)
          .select()
          .eq('id', companyId)
          .maybeSingle();
      if (response == null) return null;
      return CompanyModel.fromMap(response);
    } catch (e) {
      debugPrint('$e');
      return null;
    }
  }

  Future<List<StoreModel>> getStoresByCompanyId(String companyId) async {
    try {
      final response = await _supabase
          .from(Tables.stores)
          .select()
          .eq('company_id', companyId)
          .eq('is_active', true) // Buona pratica
          .order('name'); // O come si chiama il campo nome

      return (response as List).map((s) => StoreModel.fromMap(s)).toList();
    } catch (e) {
      debugPrint('Errore recupero negozi: $e');
      throw Exception('$e');
    }
  }

  Future<StaffMemberModel?> getStaffMemberByUserId(String userId) async {
    try {
      final response = await _supabase
          .from(Tables.staffMembers)
          .select()
          .eq('user_id', userId)
          .maybeSingle();

      if (response == null) return null;
      return StaffMemberModel.fromMap(response);
    } catch (e) {
      debugPrint('Errore recupero profilo staff: $e');
      throw Exception('$e');
    }
  }

  // --- MUTAZIONI PER L'ONBOARDING ---

  Future<CompanyModel> createCompany(CompanyModel company) async {
    try {
      final response = await _supabase
          .from(Tables.companies)
          .insert(company.toMap())
          .select()
          .single();
      return CompanyModel.fromMap(response);
    } catch (e) {
      debugPrint('Creazione azienda fallita: $e');
      throw Exception('$e');
    }
  }

  Future<StoreModel> createStore(StoreModel store) async {
    try {
      final response = await _supabase
          .from(Tables.stores)
          .insert(store.toMap())
          .select()
          .single();
      return StoreModel.fromMap(response);
    } catch (e) {
      debugPrint('Creazione negozio fallita: $e');
      throw Exception('$e');
    }
  }

  Future<StaffMemberModel> createStaffMember(StaffMemberModel staff) async {
    try {
      final response = await _supabase
          .from(Tables.staffMembers)
          .insert(staff.toMap())
          .select()
          .single();
      final StaffMemberModel staffMember = StaffMemberModel.fromMap(response);
      await _supabase.from(Tables.staffInStores).insert({
        'staff_member_id': staffMember.id,
        'store_id': GetIt.I.get<SessionCubit>().state.currentStore!.id,
      });
      return StaffMemberModel.fromMap(response);
    } catch (e) {
      debugPrint('Creazione profilo staff fallita: $e');
      throw Exception('$e');
    }
  }

  // Assegna un membro a un negozio
  Future<void> assignStaffToStore(String staffId, String storeId) async {
    await _supabase.from(Tables.staffInStores).insert({
      'staff_member_id': staffId,
      'store_id': storeId,
    });
  }

  Future<void> updateStaffMember(
    String staffId,
    Map<String, dynamic> data,
  ) async {
    await _supabase.from(Tables.staffMembers).update(data).eq('id', staffId);
  }
}
