import { Injectable } from '@angular/core';
import { ConfigService } from '@shared/config/config.service';
import { FleioApiService } from '../../fleio-api.service';
import { HttpClient } from '@angular/common/http';
import { IInvoiceModel } from '../model/invoice.model';
import { FleioId } from '../../base-model/base-fleio-object.model';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class InvoicesApiService extends FleioApiService<IInvoiceModel> {
  // noinspection JSUnusedGlobalSymbols
  constructor(protected httpClient: HttpClient, protected config: ConfigService) {
    super();
    this.setEndpoint(config.getPanelApiUrl('billing/invoices'));
  }

  refund(objectId: FleioId, refundData: {
    invoice: FleioId;
    transaction: FleioId;
    refund_to_credit: boolean;
    refund_manually: boolean;
    amount: number;
    external_id?: string;
  }) {
    return this.objectPostAction(objectId, 'perform_refund', refundData);
  }

  mergeOptions(invoices: Array<FleioId>): Observable<{
    partially_paid_inv: boolean; // whether selection has a partially paid invoice
    max_due_date: Date;
  }> {
    return this.getAction('merge_invoices_options', {invoices});
  }

  merge(invoices: Array<FleioId>, newDueDate?): Observable<any> {
    const body = {invoices} as Record<string, any>;
    if (newDueDate) {
      body.new_due_date = newDueDate;
    }
    return this.postAction('merge_invoices', body);
  }

  split(invoiceId: FleioId, items: Array<FleioId>): Observable<any> {
    return this.objectPostAction(invoiceId, 'split_invoice', {items});
  }

  splitOptions(invoiceId: FleioId, items: Array<FleioId>): Observable<{
    can_split: boolean;
    partially_paid: boolean;
    paid_after_split: boolean;
  }> {
    return this.objectGetAction(invoiceId, 'split_invoice_options', {items});
  }

  addPayment(invoiceId: FleioId, parameters: Record<string, any>): Observable<any> {
    return this.objectPostAction(invoiceId, 'add_payment_to_invoice', parameters);
  }

  payFromCredit(invoiceId: FleioId): Observable<any> {
    return this.objectPostAction(invoiceId, 'pay_from_credit_balance', {});
  }

  getSummary(): Observable<any> {
    return this.getAction('summary');
  }

  validate_credit_card_payment_opts(): Observable<any> {
    return this.postAction('validate_credit_card_payment_opts');
  }

  addCredit(credit: number): Observable<any> {
    return this.postAction('add_credit_invoice', {
      credit,
    });
  }

  getMessageTemplates(invoiceId: FleioId): Observable<any> {
    return this.objectGetAction(invoiceId, 'get_message_templates');
  }

  sendNotification(invoiceId: FleioId, templateId: FleioId): Observable<any> {
    return this.objectPostAction(invoiceId, 'send_notification', {template_id: templateId});
  }

  regeneratePDF(invoiceId: FleioId): Observable<any> {
    return this.objectPostAction(invoiceId, 'regenerate-pdf-invoice', {});
  }
}
