import { createCancelInstruction, createAuctioneerCancelInstruction, createCancelBidReceiptInstruction } from '@metaplex-foundation/mpl-auction-house';
import { SYSVAR_INSTRUCTIONS_PUBKEY } from '@solarti/web3.js';
import { AuctioneerAuthorityRequiredError } from '../errors.mjs';
import { useOperation } from '../../../types/Operation.mjs';
import { toPublicKey } from '../../../types/PublicKey.mjs';
import { TransactionBuilder } from '../../../utils/TransactionBuilder.mjs';
import { isSigner } from '../../../types/Signer.mjs';

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

const Key = 'CancelBidOperation';

/**
 * Cancels the user's bid in the given auction house.
 *
 * ```ts
 * await metaplex
 *   .auctionHouse()
 *   .cancelBid({ auctionHouse, bid };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
const cancelBidOperation = useOperation(Key);

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

/**
 * @group Operations
 * @category Handlers
 */
const cancelBidOperationHandler = {
  handle: async (operation, metaplex, scope) => cancelBidBuilder(metaplex, operation.input, scope).sendAndConfirm(metaplex, scope.confirmOptions)
};

// -----------------
// Builder
// -----------------

/**
 * @group Transaction Builders
 * @category Inputs
 */

/**
 * Cancels the user's bid in the given auction house.
 *
 * ```ts
 * const transactionBuilder = metaplex
 *   .auctionHouse()
 *   .builders()
 *   .cancelBid({ auctionHouse, bid });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
const cancelBidBuilder = (metaplex, params, options = {}) => {
  const {
    programs,
    payer = metaplex.rpc().getDefaultFeePayer()
  } = options;
  const {
    auctionHouse,
    auctioneerAuthority,
    bid
  } = params;

  // Data.
  const {
    asset,
    buyerAddress,
    tradeStateAddress,
    price,
    receiptAddress,
    tokens,
    isPublic
  } = bid;
  const {
    authorityAddress,
    address: auctionHouseAddress,
    feeAccountAddress,
    hasAuctioneer
  } = auctionHouse;
  if (hasAuctioneer && !auctioneerAuthority) {
    throw new AuctioneerAuthorityRequiredError();
  }

  // Accounts.
  const tokenAccount = isPublic ? metaplex.tokens().pdas().associatedTokenAccount({
    mint: asset.mint.address,
    owner: toPublicKey(buyerAddress),
    programs
  }) : asset.token.address;
  const accounts = {
    wallet: buyerAddress,
    tokenAccount,
    tokenMint: asset.address,
    authority: authorityAddress,
    auctionHouse: auctionHouseAddress,
    auctionHouseFeeAccount: feeAccountAddress,
    tradeState: tradeStateAddress
  };

  // Args.
  const args = {
    buyerPrice: price.basisPoints,
    tokenSize: tokens.basisPoints
  };

  // Cancel Bid Instruction.
  let cancelBidInstruction = createCancelInstruction(accounts, args);
  if (auctioneerAuthority) {
    cancelBidInstruction = createAuctioneerCancelInstruction({
      ...accounts,
      auctioneerAuthority: auctioneerAuthority.publicKey,
      ahAuctioneerPda: metaplex.auctionHouse().pdas().auctioneer({
        auctionHouse: auctionHouseAddress,
        auctioneerAuthority: auctioneerAuthority.publicKey,
        programs
      })
    }, args);
  }

  // Signers.
  const cancelSigners = [auctioneerAuthority].filter(isSigner);
  return TransactionBuilder.make().setFeePayer(payer)

  // Cancel Bid.
  .add({
    instruction: cancelBidInstruction,
    signers: cancelSigners,
    key: params.instructionKey ?? 'cancelBid'
  })

  // Cancel Bid Receipt.
  .when(Boolean(receiptAddress), builder => builder.add({
    instruction: createCancelBidReceiptInstruction({
      receipt: receiptAddress,
      instruction: SYSVAR_INSTRUCTIONS_PUBKEY
    }),
    signers: [],
    key: 'cancelBidReceipt'
  }));
};

export { cancelBidBuilder, cancelBidOperation, cancelBidOperationHandler };
//# sourceMappingURL=cancelBid.mjs.map
