import { Return } from '../models';

/**
 * Extracts all package numbers from all receipts in a return.
 * Only includes package numbers from receipts that have loaded data and where the package data exists.
 *
 * @param returnData - The return object containing receipts
 * @returns Comma-separated string of all package numbers from all receipts, or empty string if no packages found
 *
 * @example
 * ```typescript
 * const packageNumbers = getPackageNumbersFromReturn(returnData);
 * console.log(`Package numbers: ${packageNumbers}`); // "PKG-001, PKG-002, PKG-003"
 * ```
 */
export const getPackageNumbersFromReturn = (returnData: Return): string => {
  if (!returnData?.receipts || returnData.receipts.length === 0) {
    return '';
  }

  const allPackageNumbers = returnData.receipts.reduce<string[]>(
    (packageNumbers, receipt) => {
      const receiptPackages = receipt.data?.packages || [];

      // Extract package numbers from loaded packages, filtering out packages without data or packageNumber
      const receiptPackageNumbers = receiptPackages
        .filter((pkg) => pkg.data?.packageNumber)
        .map((pkg) => pkg.data!.packageNumber!);

      packageNumbers.push(...receiptPackageNumbers);
      return packageNumbers;
    },
    [],
  );

  return allPackageNumbers.join(', ');
};
