import 'dart:async';

import 'package:injectable/injectable.dart';
import 'package:krow/features/invoice/data/invoices_api_provider.dart';
import 'package:krow/features/invoice/domain/invoice_entity.dart';
import 'package:krow/features/invoice/domain/invoices_repository.dart';

@Singleton(as: InvoicesRepository)
class InvoicesRepositoryImpl extends InvoicesRepository {
  final InvoiceApiProvider _apiProvider;
  StreamController<InvoiceStatusFilterType>? _statusController;

  InvoicesRepositoryImpl({required InvoiceApiProvider apiProvider})
      : _apiProvider = apiProvider;

  @override
  Stream<InvoiceStatusFilterType> get statusStream {
    _statusController ??= StreamController<InvoiceStatusFilterType>.broadcast();
    return _statusController!.stream;
  }

  @override
  void dispose() {
    _statusController?.close();
  }

  @override
  Future<List<InvoiceListEntity>> getInvoices(
      {String? lastItemId,
      required InvoiceStatusFilterType statusFilter}) async {
    var paginationWrapper = await _apiProvider.fetchInvoices(
        statusFilter == InvoiceStatusFilterType.all ? null : statusFilter.name,
        after: lastItemId);
    return paginationWrapper.edges.map((e) {
      return InvoiceListEntity.fromModel(
        e.node,
        cursor: (paginationWrapper.pageInfo.hasNextPage) ? e.cursor : null,
      );
    }).toList();
  }

  @override
  Future<void> approveInvoice({required String invoiceId}) async{
    await  _apiProvider.approveInvoice(invoiceId: invoiceId).then((value) {
      _statusController?.add(InvoiceStatusFilterType.verified);
    });
    _statusController?.add(InvoiceStatusFilterType.all);
    _statusController?.add(InvoiceStatusFilterType.open);
  }

  @override
  Future<void> disputeInvoice({
    required String invoiceId,
    required String reason,
    required String comment,
  }) async {
    await _apiProvider.disputeInvoice(
      invoiceId: invoiceId,
      reason: reason,
      comment: comment,
    );
    _statusController?.add(InvoiceStatusFilterType.disputed);
    _statusController?.add(InvoiceStatusFilterType.all);
    _statusController?.add(InvoiceStatusFilterType.open);
  }
}
