import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_app/features/customer/domain/entities/customer.dart';
import 'package:niogu_app/features/customer/domain/repositories/i_customer_repository.dart';
import 'package:niogu_app/features/customer/presentation/providers/customer_provider.dart';

class CustomerController extends AutoDisposeAsyncNotifier<void> {
  late final ICustomerRepository _customerRepository;
  @override
  FutureOr<void> build() {
    _customerRepository = ref.read(customerRepositoryProvider);
  }

  Future<void> saveCustomer(UpsertCustomer customer) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _customerRepository.saveCustomer(customer);
    });

    state = result;

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

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

    final result = await AsyncValue.guard(() async {
      await _customerRepository.deleteCustomer(id);
    });

    state = result;

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