import { inject, Injectable } from '@angular/core';
import { OMSPrintService } from '@generated/swagger/print-api';
import { PrinterType, PrintService } from '@isa/common/print';
import { firstValueFrom } from 'rxjs';

/**
 * Service responsible for printing return receipts using the OMS print API.
 *
 * This service handles the communication with backend printing services and manages
 * the print job lifecycle through the common print infrastructure.
 */
@Injectable({ providedIn: 'root' })
export class PrintReceiptsService {
  #omsPrintService = inject(OMSPrintService);
  #printService = inject(PrintService);

  /**
   * Prints return receipts for the provided receipt IDs.
   *
   * @param options - The printing options
   * @param options.returnReceiptIds - Array of return receipt IDs to print
   * @throws {Error} When no return receipt IDs are provided
   * @returns A promise that resolves when the print job is complete
   */
  async printReturnReceipts({
    returnReceiptIds,
  }: {
    returnReceiptIds: number[];
  }) {
    if (returnReceiptIds.length === 0) {
      throw new Error('No return receipt IDs provided');
    }

    return this.#printService.print({
      printerType: PrinterType.LABEL,
      printFn: (printer) => {
        return firstValueFrom(
          this.#omsPrintService.OMSPrintReturnReceipt({
            printer: printer.key,
            data: returnReceiptIds,
          }),
        );
      },
    });
  }
}
