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/brand_model.dart';
import '../models/model_model.dart';

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

  // --- BRAND ---

  /// Recupera tutti i brand dell'azienda
  Future<List<BrandModel>> getBrands() async {
    try {
      final response = await _supabase
          .from(Tables.brands)
          .select()
          .eq('company_id', _companyId)
          .eq('is_active', true)
          .order('name');

      return (response as List).map((b) => BrandModel.fromJson(b)).toList();
    } catch (e) {
      throw 'Errore nel recupero dei Brand';
    }
  }

  /// Crea o aggiorna un brand
  Future<BrandModel> upsertBrand(BrandModel brand) async {
    try {
      final response = await _supabase
          .from(Tables.brands)
          .upsert(brand.toJson())
          .select()
          .single();

      return BrandModel.fromJson(response);
    } catch (e) {
      throw 'Errore nel salvataggio del Brand';
    }
  }

  // --- MODEL ---

  /// Recupera i modelli di un brand specifico
  Future<List<ModelModel>> getModelsByBrand(String brandId) async {
    try {
      final response = await _supabase
          .from(Tables.models)
          .select()
          .eq('brand_id', brandId)
          .eq('is_active', true)
          .order('name');

      return (response as List).map((m) => ModelModel.fromJson(m)).toList();
    } catch (e) {
      throw 'Errore nel recupero dei modelli';
    }
  }

  Future<List<ModelModel>> getModels() async {
    try {
      final response = await _supabase
          .from(Tables.models)
          .select()
          .eq('is_active', true)
          .order('name');
      return (response as List).map((m) => ModelModel.fromJson(m)).toList();
    } catch (e) {
      throw '$e';
    }
  }

  /// Crea o aggiorna un modello
  /// NOTA: name_with_brand verrà gestito dal trigger SQL che hai lanciato!
  Future<ModelModel> upsertModel(ModelModel model) async {
    try {
      final response = await _supabase
          .from(Tables.models)
          .upsert(model.toJson())
          .select()
          .single();

      return ModelModel.fromJson(response);
    } catch (e) {
      throw 'Errore nel salvataggio del modello';
    }
  }

  // --- DELETE (LOGICA) ---

  /// Disattiva un brand o un modello (Soft Delete per non rompere le FK delle operazioni passate)
  Future<void> toggleActiveStatus(String table, String id, bool status) async {
    try {
      await _supabase.from(table).update({'is_active': status}).eq('id', id);
    } catch (e) {
      throw 'Errore durante la modifica dello stato';
    }
  }

  Future<List<ModelModel>> searchModels(String query) async {
    try {
      final response = await _supabase
          .from(Tables.models)
          .select()
          .ilike('name_with_brand', '%$query%') // Cerca ovunque nel nome
          .eq('is_active', true)
          .limit(10); // Non esageriamo con i risultati

      return (response as List).map((m) => ModelModel.fromJson(m)).toList();
    } catch (e) {
      throw 'Errore durante la ricerca: $e';
    }
  }
}
