import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_app/features/goods/domain/entities/stock_card.dart';
import 'package:niogu_app/features/goods/products/presentation/providers/product_provider.dart';
import 'package:niogu_app/features/goods/domain/entities/outlet_inventory.dart';
import 'package:niogu_app/features/goods/products/domain/entities/product.dart';
import 'package:niogu_app/features/goods/products/domain/repositories/i_product_repository.dart';

class ProductController extends AutoDisposeAsyncNotifier<void> {
  late final IProductRepository _productRepository;

  @override
  FutureOr<void> build() {
    _productRepository = ref.read(productRepositoryProvider);
  }

  Future<void> saveProduct({
    required UpsertProduct product,
    required List<UpsertProductVariant> productVariants,
    List<DeleteProductVariant>? deleteVariants,
    required List<UpsertOutletInventory> outletInventories,
    required List<StockCard> stockCards,
    bool modeChange = false,
    String? modeBeforeChange,
    String? modeAfterChange,
  }) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _productRepository.saveProduct(
        product: product,
        productVariants: productVariants,
        deleteVariants: deleteVariants,
        outletInventories: outletInventories,
        stockCards: stockCards,
        modeChange: modeChange,
        modeBeforeChange: modeBeforeChange,
        modeAfterChange: modeAfterChange,
      );
    });

    state = result;

    if (result is AsyncError) throw result.error!;
  }

  Future<void> deleteProduct(
    String id, {
    String? outletId,
    required bool canDeleteAll,
  }) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _productRepository.deleteProduct(
        id,
        outletId: outletId,
        canDeleteAll: canDeleteAll,
      );
    });

    state = result;

    if (result is AsyncError) throw result.error!;
  }
}
