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

/**
 * Extracts all receipt item data from all receipts in a return.
 * Only includes items from receipts that have loaded data and where the item data exists.
 *
 * @param returnData - The return object containing receipts
 * @returns Array of all receipt item data from all receipts, or empty array if no items found
 *
 * @example
 * ```typescript
 * const items = getReceiptItemsFromReturn(returnData);
 * console.log(`Found ${items.length} receipt items across all receipts`);
 * ```
 */
export const getReceiptItemsFromReturn = (
  returnData: Return,
): ReceiptItem[] => {
  if (!returnData?.receipts || returnData.receipts.length === 0) {
    return [];
  }

  return returnData.receipts.reduce<ReceiptItem[]>((items, receipt) => {
    const receiptItems = receipt.data?.items || [];

    // Extract only the actual ReceiptItem data, filtering out items without data
    const itemData = receiptItems
      .filter((item) => item.data !== undefined)
      .map((item) => item.data!);

    items.push(...itemData);
    return items;
  }, []);
};
