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

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

const Key = 'CancelListingOperation';

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

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

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

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

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

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

  // Data.
  const {
    asset,
    sellerAddress,
    receiptAddress,
    tradeStateAddress,
    price,
    tokens
  } = listing;
  const {
    address: auctionHouseAddress,
    authorityAddress,
    feeAccountAddress,
    hasAuctioneer
  } = auctionHouse;
  if (hasAuctioneer && !auctioneerAuthority) {
    throw new AuctioneerAuthorityRequiredError();
  }
  const buyerPrice = hasAuctioneer ? AUCTIONEER_PRICE : price.basisPoints;
  const accounts = {
    wallet: sellerAddress,
    tokenAccount: asset.token.address,
    tokenMint: asset.address,
    authority: authorityAddress,
    auctionHouse: auctionHouseAddress,
    auctionHouseFeeAccount: feeAccountAddress,
    tradeState: tradeStateAddress
  };

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

  // Cancel Listing Instruction.
  let cancelListingInstruction = createCancelInstruction(accounts, args);
  if (auctioneerAuthority) {
    cancelListingInstruction = 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 Listing.
  .add({
    instruction: cancelListingInstruction,
    signers: cancelSigners,
    key: params.instructionKey ?? 'cancelListing'
  })

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

export { cancelListingBuilder, cancelListingOperation, cancelListingOperationHandler };
//# sourceMappingURL=cancelListing.mjs.map
