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

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

const Key = 'RevokeNftCollectionAuthorityOperation';

/**
 * Revokes an existing collection authority.
 *
 * ```ts
 * await metaplex
 *   .nfts()
 *   .revokeCollectionAuthority({ mintAddress, collectionAuthority };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
const revokeNftCollectionAuthorityOperation = useOperation(Key);

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

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

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

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

/**
 * Revokes an existing collection authority.
 *
 * ```ts
 * const transactionBuilder = metaplex
 *   .nfts()
 *   .builders()
 *   .revokeCollectionAuthority({ mintAddress, collectionAuthority });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
const revokeNftCollectionAuthorityBuilder = (metaplex, params, options = {}) => {
  const {
    programs,
    payer = metaplex.rpc().getDefaultFeePayer()
  } = options;
  const {
    mintAddress,
    collectionAuthority,
    revokeAuthority = metaplex.identity()
  } = params;
  const tokenMetadataProgram = metaplex.programs().getTokenMetadata(programs);
  const metadata = metaplex.nfts().pdas().metadata({
    mint: mintAddress,
    programs
  });
  const collectionAuthorityRecord = metaplex.nfts().pdas().collectionAuthorityRecord({
    mint: mintAddress,
    collectionAuthority,
    programs
  });
  const instruction = createRevokeCollectionAuthorityInstruction({
    collectionAuthorityRecord,
    delegateAuthority: collectionAuthority,
    revokeAuthority: revokeAuthority.publicKey,
    metadata,
    mint: mintAddress
  }, tokenMetadataProgram.address);

  // Temporary fix. The Shank macro wrongfully ask for the delegateAuthority to be a signer.
  // https://github.com/metaplex-foundation/metaplex-program-library/pull/639
  instruction.keys[1].isSigner = false;
  return TransactionBuilder.make().setFeePayer(payer)

  // Revoke the collection authority.
  .add({
    instruction,
    signers: [revokeAuthority],
    key: params.instructionKey ?? 'revokeCollectionAuthority'
  });
};

export { revokeNftCollectionAuthorityBuilder, revokeNftCollectionAuthorityOperation, revokeNftCollectionAuthorityOperationHandler };
//# sourceMappingURL=revokeNftCollectionAuthority.mjs.map
