/**
 * This code was AUTOGENERATED using the codama library.
 * Please DO NOT EDIT THIS FILE, instead use visitors
 * to add features, then rerun codama to update it.
 *
 * @see https://github.com/codama-idl/codama
 */

import {
  AccountRole,
  combineCodec,
  getStructDecoder,
  getStructEncoder,
  getU64Decoder,
  getU64Encoder,
  getU8Decoder,
  getU8Encoder,
  transformEncoder,
  type AccountMeta,
  type AccountSignerMeta,
  type Address,
  type FixedSizeCodec,
  type FixedSizeDecoder,
  type FixedSizeEncoder,
  type Instruction,
  type InstructionWithAccounts,
  type InstructionWithData,
  type ReadonlyAccount,
  type ReadonlySignerAccount,
  type ReadonlyUint8Array,
  type TransactionSigner,
  type WritableAccount,
} from '@solana/kit';
import { TOKEN_PROGRAM_ADDRESS } from '../programs';
import { getAccountMetaFactory, type ResolvedAccount } from '../shared';

export const TRANSFER_CHECKED_DISCRIMINATOR = 12;

export function getTransferCheckedDiscriminatorBytes() {
  return getU8Encoder().encode(TRANSFER_CHECKED_DISCRIMINATOR);
}

export type TransferCheckedInstruction<
  TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,
  TAccountSource extends string | AccountMeta<string> = string,
  TAccountMint extends string | AccountMeta<string> = string,
  TAccountDestination extends string | AccountMeta<string> = string,
  TAccountAuthority extends string | AccountMeta<string> = string,
  TRemainingAccounts extends readonly AccountMeta<string>[] = [],
> = Instruction<TProgram> &
  InstructionWithData<ReadonlyUint8Array> &
  InstructionWithAccounts<
    [
      TAccountSource extends string
        ? WritableAccount<TAccountSource>
        : TAccountSource,
      TAccountMint extends string
        ? ReadonlyAccount<TAccountMint>
        : TAccountMint,
      TAccountDestination extends string
        ? WritableAccount<TAccountDestination>
        : TAccountDestination,
      TAccountAuthority extends string
        ? ReadonlyAccount<TAccountAuthority>
        : TAccountAuthority,
      ...TRemainingAccounts,
    ]
  >;

export type TransferCheckedInstructionData = {
  discriminator: number;
  /** The amount of tokens to transfer. */
  amount: bigint;
  /** Expected number of base 10 digits to the right of the decimal place. */
  decimals: number;
};

export type TransferCheckedInstructionDataArgs = {
  /** The amount of tokens to transfer. */
  amount: number | bigint;
  /** Expected number of base 10 digits to the right of the decimal place. */
  decimals: number;
};

export function getTransferCheckedInstructionDataEncoder(): FixedSizeEncoder<TransferCheckedInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ['discriminator', getU8Encoder()],
      ['amount', getU64Encoder()],
      ['decimals', getU8Encoder()],
    ]),
    (value) => ({ ...value, discriminator: TRANSFER_CHECKED_DISCRIMINATOR })
  ) as FixedSizeEncoder<TransferCheckedInstructionDataArgs>;
}

export function getTransferCheckedInstructionDataDecoder(): FixedSizeDecoder<TransferCheckedInstructionData> {
  return getStructDecoder([
    ['discriminator', getU8Decoder()],
    ['amount', getU64Decoder()],
    ['decimals', getU8Decoder()],
  ]) as FixedSizeDecoder<TransferCheckedInstructionData>;
}

export function getTransferCheckedInstructionDataCodec(): FixedSizeCodec<
  TransferCheckedInstructionDataArgs,
  TransferCheckedInstructionData
> {
  return combineCodec(
    getTransferCheckedInstructionDataEncoder(),
    getTransferCheckedInstructionDataDecoder()
  ) as FixedSizeCodec<
    TransferCheckedInstructionDataArgs,
    TransferCheckedInstructionData
  >;
}

export type TransferCheckedInput<
  TAccountSource extends string = string,
  TAccountMint extends string = string,
  TAccountDestination extends string = string,
  TAccountAuthority extends string = string,
> = {
  /** The source account. */
  source: Address<TAccountSource>;
  /** The token mint. */
  mint: Address<TAccountMint>;
  /** The destination account. */
  destination: Address<TAccountDestination>;
  /** The source account's owner/delegate or its multisignature account. */
  authority: Address<TAccountAuthority> | TransactionSigner<TAccountAuthority>;
  amount: TransferCheckedInstructionDataArgs['amount'];
  decimals: TransferCheckedInstructionDataArgs['decimals'];
  multiSigners?: Array<TransactionSigner>;
};

export function getTransferCheckedInstruction<
  TAccountSource extends string,
  TAccountMint extends string,
  TAccountDestination extends string,
  TAccountAuthority extends string,
  TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,
>(
  input: TransferCheckedInput<
    TAccountSource,
    TAccountMint,
    TAccountDestination,
    TAccountAuthority
  >,
  config?: { programAddress?: TProgramAddress }
): TransferCheckedInstruction<
  TProgramAddress,
  TAccountSource,
  TAccountMint,
  TAccountDestination,
  (typeof input)['authority'] extends TransactionSigner<TAccountAuthority>
    ? ReadonlySignerAccount<TAccountAuthority> &
        AccountSignerMeta<TAccountAuthority>
    : TAccountAuthority
> {
  // Program address.
  const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    source: { value: input.source ?? null, isWritable: true },
    mint: { value: input.mint ?? null, isWritable: false },
    destination: { value: input.destination ?? null, isWritable: true },
    authority: { value: input.authority ?? null, isWritable: false },
  };
  const accounts = originalAccounts as Record<
    keyof typeof originalAccounts,
    ResolvedAccount
  >;

  // Original args.
  const args = { ...input };

  // Remaining accounts.
  const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(
    (signer) => ({
      address: signer.address,
      role: AccountRole.READONLY_SIGNER,
      signer,
    })
  );

  const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');
  const instruction = {
    accounts: [
      getAccountMeta(accounts.source),
      getAccountMeta(accounts.mint),
      getAccountMeta(accounts.destination),
      getAccountMeta(accounts.authority),
      ...remainingAccounts,
    ],
    programAddress,
    data: getTransferCheckedInstructionDataEncoder().encode(
      args as TransferCheckedInstructionDataArgs
    ),
  } as TransferCheckedInstruction<
    TProgramAddress,
    TAccountSource,
    TAccountMint,
    TAccountDestination,
    (typeof input)['authority'] extends TransactionSigner<TAccountAuthority>
      ? ReadonlySignerAccount<TAccountAuthority> &
          AccountSignerMeta<TAccountAuthority>
      : TAccountAuthority
  >;

  return instruction;
}

export type ParsedTransferCheckedInstruction<
  TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    /** The source account. */
    source: TAccountMetas[0];
    /** The token mint. */
    mint: TAccountMetas[1];
    /** The destination account. */
    destination: TAccountMetas[2];
    /** The source account's owner/delegate or its multisignature account. */
    authority: TAccountMetas[3];
  };
  data: TransferCheckedInstructionData;
};

export function parseTransferCheckedInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>
): ParsedTransferCheckedInstruction<TProgram, TAccountMetas> {
  if (instruction.accounts.length < 4) {
    // TODO: Coded error.
    throw new Error('Not enough accounts');
  }
  let accountIndex = 0;
  const getNextAccount = () => {
    const accountMeta = instruction.accounts![accountIndex]!;
    accountIndex += 1;
    return accountMeta;
  };
  return {
    programAddress: instruction.programAddress,
    accounts: {
      source: getNextAccount(),
      mint: getNextAccount(),
      destination: getNextAccount(),
      authority: getNextAccount(),
    },
    data: getTransferCheckedInstructionDataDecoder().decode(instruction.data),
  };
}
