import 'package:autos/data/repositories/product_repository.dart';
import 'package:autos/data/sources/remote/api_service.dart';
import 'package:autos/domain/entities/product.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/legacy.dart';

/// ✅ API SERVICE PROVIDER
final productApiServiceProvider =
    Provider<ApiService>((ref) => ApiService());

/// ✅ REPOSITORY PROVIDER
final productRepositoryProvider = Provider<ProductRepositoryImpl>((ref) {
  return ProductRepositoryImpl(ref.read(productApiServiceProvider));
});

/// ✅ PRODUCT STATE PROVIDER
final productProvider = StateNotifierProvider<ProductNotifier,
    AsyncValue<List<ProductEntity>>>((ref) {
  final repository = ref.read(productRepositoryProvider);
  return ProductNotifier(repository);
});

/// ✅ PRODUCT NOTIFIER
class ProductNotifier
    extends StateNotifier<AsyncValue<List<ProductEntity>>> {
  final ProductRepositoryImpl repository;

  ProductNotifier(this.repository)
      : super(const AsyncValue.loading());

  /// ✅ FETCH PRODUCTS (EMPTY LIST IS NOT AN ERROR!)
  Future<void> getProducts(String userId) async {
    try {
      state = const AsyncValue.loading();

      debugPrint("🚀 FETCHING PRODUCTS FOR USER ID = $userId");

      final products = await repository.getProducts(userId);

      debugPrint("✅ PRODUCTS RECEIVED = ${products.length}");

      // ✅ EVEN IF LIST IS EMPTY → SUCCESS
      state = AsyncValue.data(products);
    } catch (e, st) {
      debugPrint("❌ PRODUCT API REAL ERROR = $e");
      state = AsyncValue.error(e, st);
    }
  }

  /// ✅ CLEAR PRODUCTS SAFELY
  void clear() {
    state = const AsyncValue.data([]);
  }
}
