import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:injectable/injectable.dart';
import 'package:krow/core/application/clients/api/api_client.dart';
import 'package:krow/core/data/models/pagination_wrapper/pagination_wrapper.dart';

import 'invoices_gql.dart';
import 'models/invoice_model.dart';

@Injectable()
class InvoiceApiProvider {
  final ApiClient _client;

  InvoiceApiProvider({required ApiClient client}) : _client = client;

  Future<PaginationWrapper> fetchInvoices(String? status,
      {String? after}) async {
    final QueryResult result = await _client.query(
        schema: getInvoicesQuery,
        body: {
          if (status != null) 'status': status,
          'first': 20,
          'after': after
        });

    if (result.hasException) {
      throw Exception(result.exception.toString());
    }
    return PaginationWrapper.fromJson(
        result.data!['client_invoices'], (json) => InvoiceModel.fromJson(json));
  }

  Future<void>approveInvoice({required String invoiceId}) async{
    final QueryResult result = await _client.mutate(
        schema: approveInvoiceMutation,
        body: {
          'id': invoiceId,
        });

    if (result.hasException) {
      throw Exception(result.exception.toString());
    }
  }

  Future<void> disputeInvoice({
    required String invoiceId,
    required String reason,
    required String comment,
  }) async {
    final QueryResult result = await _client.mutate(
        schema: disputeInvoiceMutation,
        body: {
          'id': invoiceId,
          'reason': reason,
          'comment': comment,
        });

    if (result.hasException) {
      throw Exception(result.exception.toString());
    }
  }
}
