import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_app/features/supplier/domain/entities/supplier.dart';
import 'package:niogu_app/features/supplier/domain/repositories/i_supplier_repository.dart';
import 'package:niogu_app/features/supplier/presentation/providers/supplier_provider.dart';

class SupplierController extends AutoDisposeAsyncNotifier<void> {
  late final ISupplierRepository _supplierRepository;
  @override
  FutureOr<dynamic> build() {
    _supplierRepository = ref.read(supplierRepositoryProvider);
  }

  Future<void> saveSupplier(UpsertSupplier supplier) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _supplierRepository.saveSupplier(supplier);
    });

    state = result;

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

  Future<void> deleteSupplier(String id) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _supplierRepository.deleteSupplier(id);
    });

    state = result;

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

}