import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:get_it/get_it.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import '../models/provider_model.dart';
import '../models/provider_location_model.dart';

class ProviderRepository {
  final _supabase = GetIt.I.get<SupabaseClient>();
  final _companyId = GetIt.I.get<SessionCubit>().state.company!.id!;

  // 1. Carica i provider abilitati per uno specifico Store
  Future<List<ProviderModel>> getProvidersByStore(String storeId) async {
    final response = await _supabase
        .from(Tables.providersInStores)
        .select('''
          provider_id,
          provider:${Tables.providers} (
            *,
            ${Tables.providerLocations} (*)
          )
        ''')
        .eq('store_id', storeId)
        .order('name', referencedTable: 'provider');

    // Mappiamo i risultati estraendo l'oggetto 'provider' annidato
    return (response as List).map((row) {
      return ProviderModel.fromMap(row['provider'] as Map<String, dynamic>);
    }).toList();
  }

  // 2. Carica TUTTI i provider della Company (per la gestione anagrafica)
  Future<List<ProviderModel>> getAllCompanyProviders() async {
    final response = await _supabase
        .from(Tables.providers)
        .select('*, ${Tables.providerLocations} (*)')
        .order('name');

    return (response as List)
        .map((row) => ProviderModel.fromMap(row as Map<String, dynamic>))
        .toList();
  }

  // 3. Salvataggio atomico (Upsert) del Provider
  Future<ProviderModel> saveProvider(
    ProviderModel provider,
    List<String> enabledStoreIds,
  ) async {
    // A. Salva/Aggiorna il Provider principale
    final providerWithCompany = provider.copyWith(companyId: _companyId);
    final savedRow = await _supabase
        .from(Tables.providers)
        .upsert(providerWithCompany.toMap())
        .select()
        .single();

    final savedProvider = ProviderModel.fromMap(savedRow);

    // B. Sincronizza gli Store (Cancelliamo i vecchi e mettiamo i nuovi per semplicità)
    // In un'app ad alto traffico faremmo un confronto, qui l'upsert totale è più veloce da scrivere.
    await _supabase
        .from(Tables.providersInStores)
        .delete()
        .eq('provider_id', savedProvider.id!);

    if (enabledStoreIds.isNotEmpty) {
      final storeLinks = enabledStoreIds
          .map((sId) => {'provider_id': savedProvider.id, 'store_id': sId})
          .toList();

      await _supabase.from(Tables.providersInStores).insert(storeLinks);
    }

    return savedProvider;
  }

  // 4. Gestione Sedi (Locations)
  Future<void> saveLocation(ProviderLocationModel location) async {
    await _supabase.from(Tables.providerLocations).upsert(location.toMap());
  }

  Future<void> deleteLocation(String locationId) async {
    await _supabase
        .from(Tables.providerLocations)
        .delete()
        .eq('id', locationId);
  }
}
