import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_ecommerce_v1/features/order/domain/entities/order.dart';
import 'package:niogu_ecommerce_v1/features/order/domain/repositories/i_order_repository.dart';
import 'package:niogu_ecommerce_v1/features/order/presentation/providers/order_provider.dart';

class OrderController extends AutoDisposeAsyncNotifier<void> {
  late final IOrderRepository _orderRepository;

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

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

    final result = await AsyncValue.guard(() async {
      await _orderRepository.cancelOrder(orderId);
    });

    state = result;

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

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

    final result = await AsyncValue.guard(() async {
      await _orderRepository.cancellationRequest(orderId);
    });

    state = result;

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

  Future<void> reviewProduct(String orderId, List<ProductReview> reviews) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _orderRepository.reviewProduct(orderId, reviews);
    });

    state = result;

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

class OrderReportController
    extends AutoDisposeAsyncNotifier<List<OrderReport>> {
  @override
  FutureOr<List<OrderReport>> build() => _fetchOrders();

  Future<List<OrderReport>> _fetchOrders() async {
    final orderRepository = ref.read(orderRepositoryProvider);

    return await orderRepository.fetchOrders();
  }

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

    await future;
  }
}
