import { toListingReceiptAccount } from '../accounts.mjs';
import { ListingReceiptGpaBuilder } from '../gpaBuilders/ListingReceiptGpaBuilder.mjs';
import { useOperation } from '../../../types/Operation.mjs';
import { toLazyListing } from '../models/Listing.mjs';

// -----------------
// Operation
// -----------------

const Key = 'FindListingsOperation';

/**
 * Finds Listings by multiple criteria.
 *
 * ```ts
 * // Find all listings in an Auction House.
 * const listings = await metaplex
 *   .auctionHouse()
 *   .findListings({ auctionHouse });
 *
 * // Find listings by seller and mint.
 * const listings = await metaplex
 *   .auctionHouse()
 *   .findListings({ auctionHouse, seller, mint });
 * ```
 *
 * @group Operations
 * @category Constructors
 */
const findListingsOperation = useOperation(Key);

/**
 * @group Operations
 * @category Types
 */

/**
 * @group Operations
 * @category Handlers
 */
const findListingsOperationHandler = {
  handle: async (operation, metaplex, scope) => {
    const {
      commitment,
      programs
    } = scope;
    const {
      auctionHouse,
      seller,
      metadata,
      mint
    } = operation.input;
    const auctionHouseProgram = metaplex.programs().getAuctionHouse(programs);
    let listingQuery = new ListingReceiptGpaBuilder(metaplex, auctionHouseProgram.address).mergeConfig({
      commitment
    }).whereAuctionHouse(auctionHouse.address);
    if (seller) {
      listingQuery = listingQuery.whereSeller(seller);
    }
    if (metadata && !mint) {
      listingQuery = listingQuery.whereMetadata(metadata);
    }
    if (mint) {
      listingQuery = listingQuery.whereMetadata(metaplex.nfts().pdas().metadata({
        mint,
        programs
      }));
    }
    scope.throwIfCanceled();
    return listingQuery.getAndMap(account => toLazyListing(toListingReceiptAccount(account), auctionHouse));
  }
};

export { findListingsOperation, findListingsOperationHandler };
//# sourceMappingURL=findListings.mjs.map
