import { Keypair } from '@solarti/web3.js';
import { MintAuthorityMustBeSignerToMintInitialSupplyError } from '../errors.mjs';
import { useOperation, makeConfirmOptionsFinalizedOnMainnet } 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 = 'CreateTokenWithMintOperation';

/**
 * Creates both mint and token accounts in the same transaction.
 *
 * ```ts
 * const { token } = await metaplex.tokens().createTokenWithMint();
 * const mint = token.mint;
 * ```
 *
 * @group Operations
 * @category Constructors
 */
const createTokenWithMintOperation = useOperation(Key);

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

/**
 * @group Operations
 * @category Handlers
 */
const createTokenWithMintOperationHandler = {
  async handle(operation, metaplex, scope) {
    const builder = await createTokenWithMintBuilder(metaplex, operation.input, scope);
    scope.throwIfCanceled();
    const confirmOptions = makeConfirmOptionsFinalizedOnMainnet(metaplex, scope.confirmOptions);
    const output = await builder.sendAndConfirm(metaplex, confirmOptions);
    scope.throwIfCanceled();
    const token = await metaplex.tokens().findTokenWithMintByMint({
      mint: output.mintSigner.publicKey,
      address: output.tokenAddress,
      addressType: 'token'
    }, scope);
    return {
      ...output,
      token
    };
  }
};

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

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

/**
 * Creates both mint and token accounts in the same transaction.
 *
 * ```ts
 * const transactionBuilder = await metaplex.tokens().builders().createTokenWithMint();
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
const createTokenWithMintBuilder = async (metaplex, params, options = {}) => {
  const {
    programs,
    payer = metaplex.rpc().getDefaultFeePayer()
  } = options;
  const {
    decimals = 0,
    initialSupply,
    mint = Keypair.generate(),
    mintAuthority = metaplex.identity(),
    freezeAuthority = metaplex.identity().publicKey,
    owner = metaplex.identity().publicKey,
    token
  } = params;
  const createMintBuilder = await metaplex.tokens().builders().createMint({
    decimals,
    mint,
    mintAuthority: toPublicKey(mintAuthority),
    freezeAuthority,
    createAccountInstructionKey: params.createMintAccountInstructionKey ?? 'createMintAccount',
    initializeMintInstructionKey: params.initializeMintInstructionKey ?? 'initializeMint'
  }, {
    programs,
    payer
  });
  const createTokenBuilder = await metaplex.tokens().builders().createToken({
    mint: mint.publicKey,
    owner,
    token,
    createAssociatedTokenAccountInstructionKey: params.createAssociatedTokenAccountInstructionKey ?? 'createAssociatedTokenAccount',
    createAccountInstructionKey: params.createTokenAccountInstructionKey ?? 'createTokenAccount',
    initializeTokenInstructionKey: params.initializeTokenInstructionKey ?? 'initializeToken'
  }, {
    payer,
    programs
  });
  const {
    tokenAddress
  } = createTokenBuilder.getContext();
  const builder = TransactionBuilder.make().setFeePayer(payer).setContext({
    mintSigner: mint,
    tokenAddress
  })

  // Create the Mint account.
  .add(createMintBuilder)

  // Create the Token account.
  .add(createTokenBuilder);

  // Potentially mint the initial supply to the token account.
  if (!!initialSupply) {
    if (!isSigner(mintAuthority)) {
      throw new MintAuthorityMustBeSignerToMintInitialSupplyError();
    }
    builder.add(await metaplex.tokens().builders().mint({
      mintAddress: mint.publicKey,
      toToken: tokenAddress,
      amount: initialSupply,
      mintAuthority,
      mintTokensInstructionKey: params.mintTokensInstructionKey ?? 'mintTokens'
    }, {
      payer,
      programs
    }));
  }
  return builder;
};

export { createTokenWithMintBuilder, createTokenWithMintOperation, createTokenWithMintOperationHandler };
//# sourceMappingURL=createTokenWithMint.mjs.map
