import { createAddConfigLinesInstruction } from '@metaplex-solarti/mpl-candy-machine';
import { assertNotFull, assertCanAdd, assertAllConfigLineConstraints } from '../asserts.mjs';
import { useOperation } from '../../../types/Operation.mjs';
import { TransactionBuilder } from '../../../utils/TransactionBuilder.mjs';

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

const Key = 'InsertItemsToCandyMachineV2Operation';

/**
 * Insert items into an existing Candy Machine.
 *
 * ```ts
 * await metaplex
 *   .candyMachines()
 *   .insertItems({
 *     candyMachine,
 *     items: [
 *       { name: 'My NFT #1', uri: 'https://example.com/nft1' },
 *       { name: 'My NFT #2', uri: 'https://example.com/nft2' },
 *       { name: 'My NFT #3', uri: 'https://example.com/nft3' },
 *     ],
 *   };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
const insertItemsToCandyMachineV2Operation = useOperation(Key);

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

/**
 * @group Operations
 * @category Handlers
 */
const InsertItemsToCandyMachineV2OperationHandler = {
  async handle(operation, metaplex, scope) {
    return insertItemsToCandyMachineV2Builder(metaplex, operation.input, scope).sendAndConfirm(metaplex, scope.confirmOptions);
  }
};

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

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

/**
 * Insert items into an existing Candy Machine.
 *
 * ```ts
 * const transactionBuilder = metaplex
 *   .candyMachines()
 *   .builders()
 *   .insertItems({ candyMachine, items });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
const insertItemsToCandyMachineV2Builder = (metaplex, params, options = {}) => {
  const {
    payer = metaplex.rpc().getDefaultFeePayer()
  } = options;
  const authority = params.authority ?? metaplex.identity();
  const index = params.index ?? params.candyMachine.itemsLoaded;
  const {
    items
  } = params;
  assertNotFull(params.candyMachine, index);
  assertCanAdd(params.candyMachine, index, items.length);
  assertAllConfigLineConstraints(items);
  return TransactionBuilder.make().setFeePayer(payer).add({
    instruction: createAddConfigLinesInstruction({
      candyMachine: params.candyMachine.address,
      authority: authority.publicKey
    }, {
      index: index.toNumber(),
      configLines: items
    }),
    signers: [authority],
    key: params.instructionKey ?? 'insertItems'
  });
};

export { InsertItemsToCandyMachineV2OperationHandler, insertItemsToCandyMachineV2Builder, insertItemsToCandyMachineV2Operation };
//# sourceMappingURL=insertItemsToCandyMachineV2.mjs.map
