import { createMintNftInstruction, createSetCollectionDuringMintInstruction } from '@metaplex-solarti/mpl-candy-machine';
import { Keypair, SYSVAR_CLOCK_PUBKEY, SYSVAR_SLOT_HASHES_PUBKEY, SYSVAR_INSTRUCTIONS_PUBKEY } from '@solarti/web3.js';
import { parseCandyMachineV2CollectionAccount } from '../accounts.mjs';
import { assertCanMintCandyMachineV2 } from '../asserts.mjs';
import { CandyMachineV2BotTaxError } from '../errors.mjs';
import { findCandyMachineV2CreatorPda, findCandyMachineV2CollectionPda } from '../pdas.mjs';
import { useOperation, makeConfirmOptionsFinalizedOnMainnet } from '../../../types/Operation.mjs';
import { token } from '../../../types/Amount.mjs';
import { TransactionBuilder } from '../../../utils/TransactionBuilder.mjs';
import { assertAccountExists } from '../../../types/Account.mjs';

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

const Key = 'MintCandyMachineV2Operation';

/**
 * Mint an NFT from an existing Candy Machine.
 *
 * ```ts
 * const { nft } = await metaplex
 *   .candyMachinesV2()
 *   .mint({ candyMachine };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
const mintCandyMachineV2Operation = useOperation(Key);

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

/**
 * @group Operations
 * @category Handlers
 */
const mintCandyMachineV2OperationHandler = {
  async handle(operation, metaplex, scope) {
    assertCanMintCandyMachineV2(operation.input.candyMachine, scope.payer);
    const builder = await mintCandyMachineV2Builder(metaplex, operation.input, scope);
    scope.throwIfCanceled();
    const confirmOptions = makeConfirmOptionsFinalizedOnMainnet(metaplex, scope.confirmOptions);
    const output = await builder.sendAndConfirm(metaplex, confirmOptions);
    scope.throwIfCanceled();
    let nft;
    try {
      nft = await metaplex.nfts().findByMint({
        mintAddress: output.mintSigner.publicKey,
        tokenAddress: output.tokenAddress
      }, scope);
    } catch (error) {
      throw new CandyMachineV2BotTaxError(metaplex.rpc().getSolanaExporerUrl(output.response.signature), error);
    }
    return {
      nft,
      ...output
    };
  }
};

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

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

/**
 * Mint an NFT from an existing Candy Machine.
 *
 * ```ts
 * const transactionBuilder = await metaplex
 *   .candyMachinesV2()
 *   .builders()
 *   .mint({ candyMachine });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
const mintCandyMachineV2Builder = async (metaplex, params, options = {}) => {
  const {
    programs,
    payer = metaplex.rpc().getDefaultFeePayer()
  } = options;
  const {
    candyMachine,
    newMint = Keypair.generate(),
    newOwner = metaplex.identity().publicKey,
    newToken
  } = params;
  const tokenMetadataProgram = metaplex.programs().getTokenMetadata(programs).address;
  const newMetadata = metaplex.nfts().pdas().metadata({
    mint: newMint.publicKey,
    programs
  });
  const newEdition = metaplex.nfts().pdas().masterEdition({
    mint: newMint.publicKey,
    programs
  });
  const candyMachineCreator = findCandyMachineV2CreatorPda(candyMachine.address);
  const candyMachineCollectionAddress = findCandyMachineV2CollectionPda(candyMachine.address);
  const candyMachineCollectionAccount = parseCandyMachineV2CollectionAccount(await metaplex.rpc().getAccount(candyMachineCollectionAddress));
  const tokenWithMintBuilder = await metaplex.tokens().builders().createTokenWithMint({
    decimals: 0,
    initialSupply: token(1),
    mint: newMint,
    mintAuthority: payer,
    freezeAuthority: payer.publicKey,
    owner: newOwner,
    token: newToken,
    createMintAccountInstructionKey: params.createMintAccountInstructionKey,
    initializeMintInstructionKey: params.initializeMintInstructionKey,
    createAssociatedTokenAccountInstructionKey: params.createAssociatedTokenAccountInstructionKey,
    createTokenAccountInstructionKey: params.createTokenAccountInstructionKey,
    initializeTokenInstructionKey: params.initializeTokenInstructionKey,
    mintTokensInstructionKey: params.mintTokensInstructionKey
  }, {
    payer,
    programs
  });
  const {
    tokenAddress
  } = tokenWithMintBuilder.getContext();
  const mintNftInstruction = createMintNftInstruction({
    candyMachine: candyMachine.address,
    candyMachineCreator,
    payer: payer.publicKey,
    wallet: candyMachine.walletAddress,
    metadata: newMetadata,
    mint: newMint.publicKey,
    mintAuthority: payer.publicKey,
    updateAuthority: payer.publicKey,
    masterEdition: newEdition,
    tokenMetadataProgram,
    clock: SYSVAR_CLOCK_PUBKEY,
    recentBlockhashes: SYSVAR_SLOT_HASHES_PUBKEY,
    instructionSysvarAccount: SYSVAR_INSTRUCTIONS_PUBKEY
  }, {
    creatorBump: candyMachineCreator.bump
  });
  if (candyMachine.whitelistMintSettings) {
    const whitelistToken = params.whitelistToken ?? metaplex.tokens().pdas().associatedTokenAccount({
      mint: candyMachine.whitelistMintSettings.mint,
      owner: payer.publicKey
    });
    mintNftInstruction.keys.push({
      pubkey: whitelistToken,
      isWritable: true,
      isSigner: false
    }, {
      pubkey: candyMachine.whitelistMintSettings.mint,
      isWritable: true,
      isSigner: false
    }, {
      pubkey: payer.publicKey,
      isWritable: false,
      isSigner: true
    });
  }
  if (candyMachine.tokenMintAddress) {
    const payerToken = params.payerToken ?? metaplex.tokens().pdas().associatedTokenAccount({
      mint: candyMachine.tokenMintAddress,
      owner: payer.publicKey
    });
    mintNftInstruction.keys.push({
      pubkey: payerToken,
      isWritable: true,
      isSigner: false
    }, {
      pubkey: payer.publicKey,
      isWritable: false,
      isSigner: true
    });
  }
  return TransactionBuilder.make().setFeePayer(payer).setContext({
    mintSigner: newMint,
    tokenAddress
  })

  // Create token and mint accounts.
  .add(tokenWithMintBuilder)

  // Create the new NFT.
  .add({
    instruction: mintNftInstruction,
    signers: [payer, newMint],
    key: params.mintNftInstructionKey ?? 'mintNft'
  })

  // Set the collection on the NFT.
  .when(candyMachineCollectionAccount.exists, builder => {
    assertAccountExists(candyMachineCollectionAccount);
    const collectionMint = candyMachineCollectionAccount.data.mint;
    const collectionMetadata = metaplex.nfts().pdas().metadata({
      mint: collectionMint,
      programs
    });
    const collectionMasterEdition = metaplex.nfts().pdas().masterEdition({
      mint: collectionMint,
      programs
    });
    const collectionAuthorityRecord = metaplex.nfts().pdas().collectionAuthorityRecord({
      mint: collectionMint,
      collectionAuthority: candyMachineCollectionAccount.publicKey,
      programs
    });
    return builder.add({
      instruction: createSetCollectionDuringMintInstruction({
        candyMachine: candyMachine.address,
        metadata: newMetadata,
        payer: payer.publicKey,
        collectionPda: candyMachineCollectionAccount.publicKey,
        tokenMetadataProgram,
        instructions: SYSVAR_INSTRUCTIONS_PUBKEY,
        collectionMint: candyMachineCollectionAccount.data.mint,
        collectionMetadata,
        collectionMasterEdition,
        authority: candyMachine.authorityAddress,
        collectionAuthorityRecord
      }),
      signers: [payer],
      key: params.setCollectionInstructionKey ?? 'setCollection'
    });
  });
};

export { mintCandyMachineV2Builder, mintCandyMachineV2Operation, mintCandyMachineV2OperationHandler };
//# sourceMappingURL=mintCandyMachineV2.mjs.map
