import { createApproveCollectionAuthorityInstruction } from '@metaplex-solarti/mpl-token-metadata';
import { useOperation } from '../../../types/Operation.mjs';
import { TransactionBuilder } from '../../../utils/TransactionBuilder.mjs';

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

const Key = 'ApproveNftCollectionAuthorityOperation';

/**
 * Approves a new collection authority.
 *
 * ```ts
 * await metaplex
 *   .nfts()
 *   .approveCollectionAuthority({
 *     mintAddress,
 *     collectionAuthority,
 *   };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
const approveNftCollectionAuthorityOperation = useOperation(Key);

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

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

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

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

/**
 * Approves a new collection authority.
 *
 * ```ts
 * const transactionBuilder = metaplex
 *   .nfts()
 *   .builders()
 *   .approveCollectionAuthority({
 *     mintAddress,
 *     collectionAuthority,
 *   });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
const approveNftCollectionAuthorityBuilder = (metaplex, params, options = {}) => {
  const {
    programs,
    payer = metaplex.rpc().getDefaultFeePayer()
  } = options;
  const {
    mintAddress,
    collectionAuthority,
    updateAuthority = metaplex.identity()
  } = params;

  // Programs.
  const systemProgram = metaplex.programs().getSystem(programs);
  const tokenMetadataProgram = metaplex.programs().getTokenMetadata(programs);

  // PDAs.
  const metadata = metaplex.nfts().pdas().metadata({
    mint: mintAddress,
    programs
  });
  const collectionAuthorityRecord = metaplex.nfts().pdas().collectionAuthorityRecord({
    mint: mintAddress,
    collectionAuthority,
    programs
  });
  return TransactionBuilder.make().setFeePayer(payer)

  // Approve the collection authority.
  .add({
    instruction: createApproveCollectionAuthorityInstruction({
      collectionAuthorityRecord,
      newCollectionAuthority: collectionAuthority,
      updateAuthority: updateAuthority.publicKey,
      payer: payer.publicKey,
      metadata,
      mint: mintAddress,
      systemProgram: systemProgram.address
    }, tokenMetadataProgram.address),
    signers: [payer, updateAuthority],
    key: params.instructionKey ?? 'approveCollectionAuthority'
  });
};

export { approveNftCollectionAuthorityBuilder, approveNftCollectionAuthorityOperation, approveNftCollectionAuthorityOperationHandler };
//# sourceMappingURL=approveNftCollectionAuthority.mjs.map
