import { createApproveInstruction } from '@solarti/spl-token';
import { useOperation } from '../../../types/Operation.mjs';
import { token } from '../../../types/Amount.mjs';
import { isSigner } from '../../../types/Signer.mjs';
import { TransactionBuilder } from '../../../utils/TransactionBuilder.mjs';

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

const Key = 'ApproveTokenDelegateAuthorityOperation';

/**
 * Approves a delegate authority for a token account.
 *
 * ```ts
 * await metaplex
 *   .tokens()
 *   .approveDelegateAuthority({
 *     delegateAuthority,
 *     mintAddress,
 *   };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
const approveTokenDelegateAuthorityOperation = useOperation(Key);

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

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

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

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

/**
 * Approves a delegate authority for a token account.
 *
 * ```ts
 * const transactionBuilder = metaplex
 *   .tokens()
 *   .builders()
 *   .approveDelegateAuthority({
 *     delegateAuthority,
 *     mintAddress,
 *   });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
const approveTokenDelegateAuthorityBuilder = (metaplex, params, options = {}) => {
  const {
    programs,
    payer = metaplex.rpc().getDefaultFeePayer()
  } = options;
  const {
    mintAddress,
    delegateAuthority,
    amount = token(1),
    owner = metaplex.identity(),
    tokenAddress,
    multiSigners = []
  } = params;
  const [ownerPublicKey, signers] = isSigner(owner) ? [owner.publicKey, [owner]] : [owner, multiSigners];
  const tokenProgram = metaplex.programs().getToken(programs);
  const tokenAddressOrAta = tokenAddress ?? metaplex.tokens().pdas().associatedTokenAccount({
    mint: mintAddress,
    owner: ownerPublicKey,
    programs
  });
  return TransactionBuilder.make().setFeePayer(payer).add({
    instruction: createApproveInstruction(tokenAddressOrAta, delegateAuthority, ownerPublicKey, amount.basisPoints.toNumber(), multiSigners, tokenProgram.address),
    signers,
    key: params.instructionKey ?? 'approveDelegateAuthority'
  });
};

export { approveTokenDelegateAuthorityBuilder, approveTokenDelegateAuthorityOperation, approveTokenDelegateAuthorityOperationHandler };
//# sourceMappingURL=approveTokenDelegateAuthority.mjs.map
