/**
 * 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,
  fixDecoderSize,
  fixEncoderSize,
  getBytesDecoder,
  getBytesEncoder,
  getStructDecoder,
  getStructEncoder,
  transformEncoder,
  type AccountMeta,
  type Address,
  type FixedSizeCodec,
  type FixedSizeDecoder,
  type FixedSizeEncoder,
  type Instruction,
  type InstructionWithAccounts,
  type InstructionWithData,
  type ReadonlyAccount,
  type ReadonlyUint8Array,
  type WritableAccount,
} from "@solana/kit";
import { findEventAuthorityPda, findRentFundPda, findStatePda } from "../pdas";
import { SPONSORED_CCTP_SRC_PERIPHERY_PROGRAM_ADDRESS } from "../programs";
import { getAccountMetaFactory, type ResolvedAccount } from "../shared";
import {
  getUsedNonceAccountParamsDecoder,
  getUsedNonceAccountParamsEncoder,
  type UsedNonceAccountParams,
  type UsedNonceAccountParamsArgs,
} from "../types";

export const RECLAIM_USED_NONCE_ACCOUNT_DISCRIMINATOR = new Uint8Array([
  153, 152, 111, 172, 156, 104, 116, 3,
]);

export function getReclaimUsedNonceAccountDiscriminatorBytes() {
  return fixEncoderSize(getBytesEncoder(), 8).encode(
    RECLAIM_USED_NONCE_ACCOUNT_DISCRIMINATOR,
  );
}

export type ReclaimUsedNonceAccountInstruction<
  TProgram extends string = typeof SPONSORED_CCTP_SRC_PERIPHERY_PROGRAM_ADDRESS,
  TAccountState extends string | AccountMeta<string> = string,
  TAccountRentFund extends string | AccountMeta<string> = string,
  TAccountUsedNonce extends string | AccountMeta<string> = string,
  TAccountEventAuthority extends string | AccountMeta<string> = string,
  TAccountProgram extends string | AccountMeta<string> = string,
  TRemainingAccounts extends readonly AccountMeta<string>[] = [],
> = Instruction<TProgram> &
  InstructionWithData<ReadonlyUint8Array> &
  InstructionWithAccounts<
    [
      TAccountState extends string
        ? ReadonlyAccount<TAccountState>
        : TAccountState,
      TAccountRentFund extends string
        ? WritableAccount<TAccountRentFund>
        : TAccountRentFund,
      TAccountUsedNonce extends string
        ? WritableAccount<TAccountUsedNonce>
        : TAccountUsedNonce,
      TAccountEventAuthority extends string
        ? ReadonlyAccount<TAccountEventAuthority>
        : TAccountEventAuthority,
      TAccountProgram extends string
        ? ReadonlyAccount<TAccountProgram>
        : TAccountProgram,
      ...TRemainingAccounts,
    ]
  >;

export type ReclaimUsedNonceAccountInstructionData = {
  discriminator: ReadonlyUint8Array;
  params: UsedNonceAccountParams;
};

export type ReclaimUsedNonceAccountInstructionDataArgs = {
  params: UsedNonceAccountParamsArgs;
};

export function getReclaimUsedNonceAccountInstructionDataEncoder(): FixedSizeEncoder<ReclaimUsedNonceAccountInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", fixEncoderSize(getBytesEncoder(), 8)],
      ["params", getUsedNonceAccountParamsEncoder()],
    ]),
    (value) => ({
      ...value,
      discriminator: RECLAIM_USED_NONCE_ACCOUNT_DISCRIMINATOR,
    }),
  );
}

export function getReclaimUsedNonceAccountInstructionDataDecoder(): FixedSizeDecoder<ReclaimUsedNonceAccountInstructionData> {
  return getStructDecoder([
    ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
    ["params", getUsedNonceAccountParamsDecoder()],
  ]);
}

export function getReclaimUsedNonceAccountInstructionDataCodec(): FixedSizeCodec<
  ReclaimUsedNonceAccountInstructionDataArgs,
  ReclaimUsedNonceAccountInstructionData
> {
  return combineCodec(
    getReclaimUsedNonceAccountInstructionDataEncoder(),
    getReclaimUsedNonceAccountInstructionDataDecoder(),
  );
}

export type ReclaimUsedNonceAccountAsyncInput<
  TAccountState extends string = string,
  TAccountRentFund extends string = string,
  TAccountUsedNonce extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  state?: Address<TAccountState>;
  rentFund?: Address<TAccountRentFund>;
  usedNonce: Address<TAccountUsedNonce>;
  eventAuthority?: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  params: ReclaimUsedNonceAccountInstructionDataArgs["params"];
};

export async function getReclaimUsedNonceAccountInstructionAsync<
  TAccountState extends string,
  TAccountRentFund extends string,
  TAccountUsedNonce extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address =
    typeof SPONSORED_CCTP_SRC_PERIPHERY_PROGRAM_ADDRESS,
>(
  input: ReclaimUsedNonceAccountAsyncInput<
    TAccountState,
    TAccountRentFund,
    TAccountUsedNonce,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): Promise<
  ReclaimUsedNonceAccountInstruction<
    TProgramAddress,
    TAccountState,
    TAccountRentFund,
    TAccountUsedNonce,
    TAccountEventAuthority,
    TAccountProgram
  >
> {
  // Program address.
  const programAddress =
    config?.programAddress ?? SPONSORED_CCTP_SRC_PERIPHERY_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    state: { value: input.state ?? null, isWritable: false },
    rentFund: { value: input.rentFund ?? null, isWritable: true },
    usedNonce: { value: input.usedNonce ?? null, isWritable: true },
    eventAuthority: { value: input.eventAuthority ?? null, isWritable: false },
    program: { value: input.program ?? null, isWritable: false },
  };
  const accounts = originalAccounts as Record<
    keyof typeof originalAccounts,
    ResolvedAccount
  >;

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

  // Resolve default values.
  if (!accounts.state.value) {
    accounts.state.value = await findStatePda();
  }
  if (!accounts.rentFund.value) {
    accounts.rentFund.value = await findRentFundPda();
  }
  if (!accounts.eventAuthority.value) {
    accounts.eventAuthority.value = await findEventAuthorityPda();
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta(accounts.state),
      getAccountMeta(accounts.rentFund),
      getAccountMeta(accounts.usedNonce),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getReclaimUsedNonceAccountInstructionDataEncoder().encode(
      args as ReclaimUsedNonceAccountInstructionDataArgs,
    ),
    programAddress,
  } as ReclaimUsedNonceAccountInstruction<
    TProgramAddress,
    TAccountState,
    TAccountRentFund,
    TAccountUsedNonce,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type ReclaimUsedNonceAccountInput<
  TAccountState extends string = string,
  TAccountRentFund extends string = string,
  TAccountUsedNonce extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  state: Address<TAccountState>;
  rentFund: Address<TAccountRentFund>;
  usedNonce: Address<TAccountUsedNonce>;
  eventAuthority: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  params: ReclaimUsedNonceAccountInstructionDataArgs["params"];
};

export function getReclaimUsedNonceAccountInstruction<
  TAccountState extends string,
  TAccountRentFund extends string,
  TAccountUsedNonce extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address =
    typeof SPONSORED_CCTP_SRC_PERIPHERY_PROGRAM_ADDRESS,
>(
  input: ReclaimUsedNonceAccountInput<
    TAccountState,
    TAccountRentFund,
    TAccountUsedNonce,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): ReclaimUsedNonceAccountInstruction<
  TProgramAddress,
  TAccountState,
  TAccountRentFund,
  TAccountUsedNonce,
  TAccountEventAuthority,
  TAccountProgram
> {
  // Program address.
  const programAddress =
    config?.programAddress ?? SPONSORED_CCTP_SRC_PERIPHERY_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    state: { value: input.state ?? null, isWritable: false },
    rentFund: { value: input.rentFund ?? null, isWritable: true },
    usedNonce: { value: input.usedNonce ?? null, isWritable: true },
    eventAuthority: { value: input.eventAuthority ?? null, isWritable: false },
    program: { value: input.program ?? null, isWritable: false },
  };
  const accounts = originalAccounts as Record<
    keyof typeof originalAccounts,
    ResolvedAccount
  >;

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

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta(accounts.state),
      getAccountMeta(accounts.rentFund),
      getAccountMeta(accounts.usedNonce),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getReclaimUsedNonceAccountInstructionDataEncoder().encode(
      args as ReclaimUsedNonceAccountInstructionDataArgs,
    ),
    programAddress,
  } as ReclaimUsedNonceAccountInstruction<
    TProgramAddress,
    TAccountState,
    TAccountRentFund,
    TAccountUsedNonce,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type ParsedReclaimUsedNonceAccountInstruction<
  TProgram extends string = typeof SPONSORED_CCTP_SRC_PERIPHERY_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    state: TAccountMetas[0];
    rentFund: TAccountMetas[1];
    usedNonce: TAccountMetas[2];
    eventAuthority: TAccountMetas[3];
    program: TAccountMetas[4];
  };
  data: ReclaimUsedNonceAccountInstructionData;
};

export function parseReclaimUsedNonceAccountInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>,
): ParsedReclaimUsedNonceAccountInstruction<TProgram, TAccountMetas> {
  if (instruction.accounts.length < 5) {
    // TODO: Coded error.
    throw new Error("Not enough accounts");
  }
  let accountIndex = 0;
  const getNextAccount = () => {
    const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;
    accountIndex += 1;
    return accountMeta;
  };
  return {
    programAddress: instruction.programAddress,
    accounts: {
      state: getNextAccount(),
      rentFund: getNextAccount(),
      usedNonce: getNextAccount(),
      eventAuthority: getNextAccount(),
      program: getNextAccount(),
    },
    data: getReclaimUsedNonceAccountInstructionDataDecoder().decode(
      instruction.data,
    ),
  };
}
