import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_ecommerce_v1/features/checkout/domain/entities/checkout.dart';
import 'package:niogu_ecommerce_v1/features/checkout/domain/repositories/i_checkout_repository.dart';
import 'package:niogu_ecommerce_v1/features/checkout/presentation/providers/checkout_provider.dart';

class CheckoutController extends AutoDisposeAsyncNotifier<void> {
  late final ICheckoutRepository _checkoutRepository;

  @override
  FutureOr<void> build() {
    // TODO: implement build
    _checkoutRepository = ref.read(checkoutRepositoryProvider);
  }

  Future<Checkout?> checkout(OnlineOrder order) async {
    state = const AsyncValue.loading();

    Checkout? data;

    final result = await AsyncValue.guard(() async {
      data = await _checkoutRepository.checkout(order);
    });

    state = result;

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