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

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

const Key = 'ThawDelegatedNftOperation';

/**
 * Thaws a NFT via its delegate authority.
 *
 * ```ts
 * await metaplex
 *   .nfts()
 *   .thawDelegatedNft({ mintAddress, delegateAuthority };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
const thawDelegatedNftOperation = useOperation(Key);

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

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

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

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

/**
 * Thaws a NFT via its delegate authority.
 *
 * ```ts
 * const transactionBuilder = metaplex
 *   .nfts()
 *   .builders()
 *   .thawDelegatedNft({ mintAddress, delegateAuthority });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
const thawDelegatedNftBuilder = (metaplex, params, options = {}) => {
  const {
    programs,
    payer = metaplex.rpc().getDefaultFeePayer()
  } = options;
  const {
    mintAddress,
    delegateAuthority,
    tokenOwner = metaplex.identity().publicKey,
    tokenAddress
  } = params;

  // Programs.
  const tokenProgram = metaplex.programs().getToken(programs);
  const tokenMetadataProgram = metaplex.programs().getTokenMetadata(programs);
  const editionAddress = metaplex.nfts().pdas().masterEdition({
    mint: mintAddress,
    programs
  });
  const tokenAddressOrAta = tokenAddress ?? metaplex.tokens().pdas().associatedTokenAccount({
    mint: mintAddress,
    owner: tokenOwner,
    programs
  });
  return TransactionBuilder.make().setFeePayer(payer).add({
    instruction: createThawDelegatedAccountInstruction({
      delegate: delegateAuthority.publicKey,
      tokenAccount: tokenAddressOrAta,
      edition: editionAddress,
      mint: mintAddress,
      tokenProgram: tokenProgram.address
    }, tokenMetadataProgram.address),
    signers: [delegateAuthority],
    key: params.instructionKey ?? 'thawDelegatedNft'
  });
};

export { thawDelegatedNftBuilder, thawDelegatedNftOperation, thawDelegatedNftOperationHandler };
//# sourceMappingURL=thawDelegatedNft.mjs.map
