import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_ecommerce_v1/core/models/tenant_model.dart';
import 'package:niogu_ecommerce_v1/features/home/domain/entities/home.dart';
import 'package:niogu_ecommerce_v1/features/home/presentation/providers/home_provider.dart';

class ConfigurationController extends AutoDisposeAsyncNotifier<TenantModel?> {
  @override
  FutureOr<TenantModel?> build() => _fetchConfiguration();

  Future<TenantModel?> _fetchConfiguration() async {
    final homeRepository = ref.read(homeRepositoryProvider);

    return await homeRepository.fetchConfiguration();
  }

  Future<void> refresh() async {
    ref.invalidateSelf();

    await future;
  }
}

class HomeController extends AutoDisposeAsyncNotifier<Home?> {
  @override
  FutureOr<Home?> build() => _fetchHome();

  Future<Home?> _fetchHome() async {
    final homeRepository = ref.read(homeRepositoryProvider);

    return await homeRepository.fetchHome();
  }

  Future<void> refresh() async {
    ref.invalidateSelf();

    await future;
  }
}

class ProductByNameController
    extends AutoDisposeFamilyAsyncNotifier<List<ProductItem>, String> {
  @override
  FutureOr<List<ProductItem>> build(String name) => _fetchProductByName(name);

  Future<List<ProductItem>> _fetchProductByName(String name) async {
    final homeRepository = ref.read(homeRepositoryProvider);

    return await homeRepository.fetchProductByName(name);
  }

  Future<void> refresh() async {
    ref.invalidateSelf();

    await future;
  }
}

class ProductCategoryController
    extends AutoDisposeFamilyAsyncNotifier<List<ProductItem>, String> {
  @override
  FutureOr<List<ProductItem>> build(String categoryId) =>
      _fetchProductBestSellers(categoryId);

  Future<List<ProductItem>> _fetchProductBestSellers(String categoryId) async {
    final homeRepository = ref.read(homeRepositoryProvider);

    return await homeRepository.fetchProductCategories(categoryId);
  }

  Future<void> refresh() async {
    ref.invalidateSelf();

    await future;
  }
}
