/**
 * 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 {
  combineCodec,
  getAddressDecoder,
  getAddressEncoder,
  getOptionDecoder,
  getOptionEncoder,
  getProgramDerivedAddress,
  getStructDecoder,
  getStructEncoder,
  getU64Decoder,
  getU64Encoder,
  getU8Decoder,
  getU8Encoder,
  SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS,
  SolanaError,
  transformEncoder,
  type AccountMeta,
  type AccountSignerMeta,
  type Address,
  type Codec,
  type Decoder,
  type Encoder,
  type Instruction,
  type InstructionWithAccounts,
  type InstructionWithData,
  type Option,
  type OptionOrNullable,
  type ReadonlyAccount,
  type ReadonlySignerAccount,
  type ReadonlyUint8Array,
  type TransactionSigner,
  type WritableAccount,
} from "@solana/kit";
import {
  getAccountMetaFactory,
  getAddressFromResolvedInstructionAccount,
  type ResolvedInstructionAccount,
} from "@solana/kit/program-client-core";
import { PRIVATE_CHANNEL_WITHDRAW_PROGRAM_PROGRAM_ADDRESS } from "../programs";

export const WITHDRAW_FUNDS_DISCRIMINATOR = 0;

export function getWithdrawFundsDiscriminatorBytes(): ReadonlyUint8Array {
  return getU8Encoder().encode(WITHDRAW_FUNDS_DISCRIMINATOR);
}

export type WithdrawFundsInstruction<
  TProgram extends string =
    typeof PRIVATE_CHANNEL_WITHDRAW_PROGRAM_PROGRAM_ADDRESS,
  TAccountUser extends string | AccountMeta<string> = string,
  TAccountMint extends string | AccountMeta<string> = string,
  TAccountTokenAccount extends string | AccountMeta<string> = string,
  TAccountTokenProgram extends string | AccountMeta<string> =
    "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
  TAccountAssociatedTokenProgram extends string | AccountMeta<string> =
    "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",
  TRemainingAccounts extends readonly AccountMeta<string>[] = [],
> = Instruction<TProgram> &
  InstructionWithData<ReadonlyUint8Array> &
  InstructionWithAccounts<
    [
      TAccountUser extends string
        ? ReadonlySignerAccount<TAccountUser> & AccountSignerMeta<TAccountUser>
        : TAccountUser,
      TAccountMint extends string
        ? WritableAccount<TAccountMint>
        : TAccountMint,
      TAccountTokenAccount extends string
        ? WritableAccount<TAccountTokenAccount>
        : TAccountTokenAccount,
      TAccountTokenProgram extends string
        ? ReadonlyAccount<TAccountTokenProgram>
        : TAccountTokenProgram,
      TAccountAssociatedTokenProgram extends string
        ? ReadonlyAccount<TAccountAssociatedTokenProgram>
        : TAccountAssociatedTokenProgram,
      ...TRemainingAccounts,
    ]
  >;

export type WithdrawFundsInstructionData = {
  discriminator: number;
  amount: bigint;
  destination: Option<Address>;
};

export type WithdrawFundsInstructionDataArgs = {
  amount: number | bigint;
  destination: OptionOrNullable<Address>;
};

export function getWithdrawFundsInstructionDataEncoder(): Encoder<WithdrawFundsInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", getU8Encoder()],
      ["amount", getU64Encoder()],
      ["destination", getOptionEncoder(getAddressEncoder())],
    ]),
    (value) => ({ ...value, discriminator: WITHDRAW_FUNDS_DISCRIMINATOR }),
  );
}

export function getWithdrawFundsInstructionDataDecoder(): Decoder<WithdrawFundsInstructionData> {
  return getStructDecoder([
    ["discriminator", getU8Decoder()],
    ["amount", getU64Decoder()],
    ["destination", getOptionDecoder(getAddressDecoder())],
  ]);
}

export function getWithdrawFundsInstructionDataCodec(): Codec<
  WithdrawFundsInstructionDataArgs,
  WithdrawFundsInstructionData
> {
  return combineCodec(
    getWithdrawFundsInstructionDataEncoder(),
    getWithdrawFundsInstructionDataDecoder(),
  );
}

export type WithdrawFundsAsyncInput<
  TAccountUser extends string = string,
  TAccountMint extends string = string,
  TAccountTokenAccount extends string = string,
  TAccountTokenProgram extends string = string,
  TAccountAssociatedTokenProgram extends string = string,
> = {
  /** User initiating the withdrawal */
  user: TransactionSigner<TAccountUser>;
  /** Token mint */
  mint: Address<TAccountMint>;
  /** Source token account */
  tokenAccount?: Address<TAccountTokenAccount>;
  /** Token program */
  tokenProgram?: Address<TAccountTokenProgram>;
  /** Associated token program */
  associatedTokenProgram?: Address<TAccountAssociatedTokenProgram>;
  amount: WithdrawFundsInstructionDataArgs["amount"];
  destination: WithdrawFundsInstructionDataArgs["destination"];
};

export async function getWithdrawFundsInstructionAsync<
  TAccountUser extends string,
  TAccountMint extends string,
  TAccountTokenAccount extends string,
  TAccountTokenProgram extends string,
  TAccountAssociatedTokenProgram extends string,
  TProgramAddress extends Address =
    typeof PRIVATE_CHANNEL_WITHDRAW_PROGRAM_PROGRAM_ADDRESS,
>(
  input: WithdrawFundsAsyncInput<
    TAccountUser,
    TAccountMint,
    TAccountTokenAccount,
    TAccountTokenProgram,
    TAccountAssociatedTokenProgram
  >,
  config?: { programAddress?: TProgramAddress },
): Promise<
  WithdrawFundsInstruction<
    TProgramAddress,
    TAccountUser,
    TAccountMint,
    TAccountTokenAccount,
    TAccountTokenProgram,
    TAccountAssociatedTokenProgram
  >
> {
  // Program address.
  const programAddress =
    config?.programAddress ?? PRIVATE_CHANNEL_WITHDRAW_PROGRAM_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    user: { value: input.user ?? null, isWritable: false },
    mint: { value: input.mint ?? null, isWritable: true },
    tokenAccount: { value: input.tokenAccount ?? null, isWritable: true },
    tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },
    associatedTokenProgram: {
      value: input.associatedTokenProgram ?? null,
      isWritable: false,
    },
  };
  const accounts = originalAccounts as Record<
    keyof typeof originalAccounts,
    ResolvedInstructionAccount
  >;

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

  // Resolve default values.
  if (!accounts.tokenProgram.value) {
    accounts.tokenProgram.value =
      "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" as Address<"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA">;
  }
  if (!accounts.tokenAccount.value) {
    accounts.tokenAccount.value = await getProgramDerivedAddress({
      programAddress:
        "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" as Address<"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL">,
      seeds: [
        getAddressEncoder().encode(
          getAddressFromResolvedInstructionAccount("user", accounts.user.value),
        ),
        getAddressEncoder().encode(
          getAddressFromResolvedInstructionAccount(
            "tokenProgram",
            accounts.tokenProgram.value,
          ),
        ),
        getAddressEncoder().encode(
          getAddressFromResolvedInstructionAccount("mint", accounts.mint.value),
        ),
      ],
    });
  }
  if (!accounts.associatedTokenProgram.value) {
    accounts.associatedTokenProgram.value =
      "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" as Address<"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL">;
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta("user", accounts.user),
      getAccountMeta("mint", accounts.mint),
      getAccountMeta("tokenAccount", accounts.tokenAccount),
      getAccountMeta("tokenProgram", accounts.tokenProgram),
      getAccountMeta("associatedTokenProgram", accounts.associatedTokenProgram),
    ],
    data: getWithdrawFundsInstructionDataEncoder().encode(
      args as WithdrawFundsInstructionDataArgs,
    ),
    programAddress,
  } as WithdrawFundsInstruction<
    TProgramAddress,
    TAccountUser,
    TAccountMint,
    TAccountTokenAccount,
    TAccountTokenProgram,
    TAccountAssociatedTokenProgram
  >);
}

export type WithdrawFundsInput<
  TAccountUser extends string = string,
  TAccountMint extends string = string,
  TAccountTokenAccount extends string = string,
  TAccountTokenProgram extends string = string,
  TAccountAssociatedTokenProgram extends string = string,
> = {
  /** User initiating the withdrawal */
  user: TransactionSigner<TAccountUser>;
  /** Token mint */
  mint: Address<TAccountMint>;
  /** Source token account */
  tokenAccount: Address<TAccountTokenAccount>;
  /** Token program */
  tokenProgram?: Address<TAccountTokenProgram>;
  /** Associated token program */
  associatedTokenProgram?: Address<TAccountAssociatedTokenProgram>;
  amount: WithdrawFundsInstructionDataArgs["amount"];
  destination: WithdrawFundsInstructionDataArgs["destination"];
};

export function getWithdrawFundsInstruction<
  TAccountUser extends string,
  TAccountMint extends string,
  TAccountTokenAccount extends string,
  TAccountTokenProgram extends string,
  TAccountAssociatedTokenProgram extends string,
  TProgramAddress extends Address =
    typeof PRIVATE_CHANNEL_WITHDRAW_PROGRAM_PROGRAM_ADDRESS,
>(
  input: WithdrawFundsInput<
    TAccountUser,
    TAccountMint,
    TAccountTokenAccount,
    TAccountTokenProgram,
    TAccountAssociatedTokenProgram
  >,
  config?: { programAddress?: TProgramAddress },
): WithdrawFundsInstruction<
  TProgramAddress,
  TAccountUser,
  TAccountMint,
  TAccountTokenAccount,
  TAccountTokenProgram,
  TAccountAssociatedTokenProgram
> {
  // Program address.
  const programAddress =
    config?.programAddress ?? PRIVATE_CHANNEL_WITHDRAW_PROGRAM_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    user: { value: input.user ?? null, isWritable: false },
    mint: { value: input.mint ?? null, isWritable: true },
    tokenAccount: { value: input.tokenAccount ?? null, isWritable: true },
    tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },
    associatedTokenProgram: {
      value: input.associatedTokenProgram ?? null,
      isWritable: false,
    },
  };
  const accounts = originalAccounts as Record<
    keyof typeof originalAccounts,
    ResolvedInstructionAccount
  >;

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

  // Resolve default values.
  if (!accounts.tokenProgram.value) {
    accounts.tokenProgram.value =
      "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" as Address<"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA">;
  }
  if (!accounts.associatedTokenProgram.value) {
    accounts.associatedTokenProgram.value =
      "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" as Address<"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL">;
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta("user", accounts.user),
      getAccountMeta("mint", accounts.mint),
      getAccountMeta("tokenAccount", accounts.tokenAccount),
      getAccountMeta("tokenProgram", accounts.tokenProgram),
      getAccountMeta("associatedTokenProgram", accounts.associatedTokenProgram),
    ],
    data: getWithdrawFundsInstructionDataEncoder().encode(
      args as WithdrawFundsInstructionDataArgs,
    ),
    programAddress,
  } as WithdrawFundsInstruction<
    TProgramAddress,
    TAccountUser,
    TAccountMint,
    TAccountTokenAccount,
    TAccountTokenProgram,
    TAccountAssociatedTokenProgram
  >);
}

export type ParsedWithdrawFundsInstruction<
  TProgram extends string =
    typeof PRIVATE_CHANNEL_WITHDRAW_PROGRAM_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    /** User initiating the withdrawal */
    user: TAccountMetas[0];
    /** Token mint */
    mint: TAccountMetas[1];
    /** Source token account */
    tokenAccount: TAccountMetas[2];
    /** Token program */
    tokenProgram: TAccountMetas[3];
    /** Associated token program */
    associatedTokenProgram: TAccountMetas[4];
  };
  data: WithdrawFundsInstructionData;
};

export function parseWithdrawFundsInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>,
): ParsedWithdrawFundsInstruction<TProgram, TAccountMetas> {
  if (instruction.accounts.length < 5) {
    throw new SolanaError(
      SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS,
      {
        actualAccountMetas: instruction.accounts.length,
        expectedAccountMetas: 5,
      },
    );
  }
  let accountIndex = 0;
  const getNextAccount = () => {
    const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;
    accountIndex += 1;
    return accountMeta;
  };
  return {
    programAddress: instruction.programAddress,
    accounts: {
      user: getNextAccount(),
      mint: getNextAccount(),
      tokenAccount: getNextAccount(),
      tokenProgram: getNextAccount(),
      associatedTokenProgram: getNextAccount(),
    },
    data: getWithdrawFundsInstructionDataDecoder().decode(instruction.data),
  };
}
