import { toBidReceiptAccount } from '../accounts.mjs';
import { BidReceiptGpaBuilder } from '../gpaBuilders/BidReceiptGpaBuilder.mjs';
import { UnreachableCaseError } from '../../../errors/SdkError.mjs';
import { useOperation } from '../../../types/Operation.mjs';
import { toLazyBid } from '../models/Bid.mjs';

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

const Key = 'FindBidsByPublicKeyOperation';

/**
 * Finds multiple Bids by specific criteria.
 *
 * ```ts
 * // Find bids by buyer.
 * const bids = await metaplex
 *   .auctionHouse()
 *   .findBidsBy({ auctionHouse, type: 'buyer', publicKey: buyer };
 *
 * // Find bids by metadata.
 * const bids = await metaplex
 *   .auctionHouse()
 *   .findBidsBy({ auctionHouse, type: 'metadata', publicKey: metadata };
 *
 * // Find bids by mint.
 * const bids = await metaplex
 *   .auctionHouse()
 *   .findBidsBy({ auctionHouse, type: 'mint', publicKey: mint };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
const findBidsByPublicKeyFieldOperation = useOperation(Key);

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

/**
 * @group Operations
 * @category Handlers
 */
const findBidsByPublicKeyFieldOperationHandler = {
  handle: async (operation, metaplex, scope) => {
    const {
      programs,
      commitment
    } = scope;
    const {
      auctionHouse,
      type,
      publicKey
    } = operation.input;
    const auctionHouseProgram = metaplex.programs().getAuctionHouse();
    let bidQuery = new BidReceiptGpaBuilder(metaplex, auctionHouseProgram.address).mergeConfig({
      commitment
    }).whereAuctionHouse(auctionHouse.address);
    switch (type) {
      case 'buyer':
        bidQuery = bidQuery.whereBuyer(publicKey);
        break;
      case 'metadata':
        bidQuery = bidQuery.whereMetadata(publicKey);
        break;
      case 'mint':
        bidQuery = bidQuery.whereMetadata(metaplex.nfts().pdas().metadata({
          mint: publicKey,
          programs
        }));
        break;
      default:
        throw new UnreachableCaseError(type);
    }
    scope.throwIfCanceled();
    return bidQuery.getAndMap(account => toLazyBid(toBidReceiptAccount(account), auctionHouse));
  }
};

export { findBidsByPublicKeyFieldOperation, findBidsByPublicKeyFieldOperationHandler };
//# sourceMappingURL=findBidsByPublicKeyField.mjs.map
