/**
 * 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,
  getStructDecoder,
  getStructEncoder,
  getU32Decoder,
  getU32Encoder,
  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 { SYSTEM_PROGRAM_ADDRESS } from '../programs';
import { getAccountMetaFactory, type ResolvedAccount } from '../shared';

export const INITIALIZE_NONCE_ACCOUNT_DISCRIMINATOR = 6;

export function getInitializeNonceAccountDiscriminatorBytes() {
  return getU32Encoder().encode(INITIALIZE_NONCE_ACCOUNT_DISCRIMINATOR);
}

export type InitializeNonceAccountInstruction<
  TProgram extends string = typeof SYSTEM_PROGRAM_ADDRESS,
  TAccountNonceAccount extends string | AccountMeta<string> = string,
  TAccountRecentBlockhashesSysvar extends
    | string
    | AccountMeta<string> = 'SysvarRecentB1ockHashes11111111111111111111',
  TAccountRentSysvar extends
    | string
    | AccountMeta<string> = 'SysvarRent111111111111111111111111111111111',
  TRemainingAccounts extends readonly AccountMeta<string>[] = [],
> = Instruction<TProgram> &
  InstructionWithData<ReadonlyUint8Array> &
  InstructionWithAccounts<
    [
      TAccountNonceAccount extends string
        ? WritableAccount<TAccountNonceAccount>
        : TAccountNonceAccount,
      TAccountRecentBlockhashesSysvar extends string
        ? ReadonlyAccount<TAccountRecentBlockhashesSysvar>
        : TAccountRecentBlockhashesSysvar,
      TAccountRentSysvar extends string
        ? ReadonlyAccount<TAccountRentSysvar>
        : TAccountRentSysvar,
      ...TRemainingAccounts,
    ]
  >;

export type InitializeNonceAccountInstructionData = {
  discriminator: number;
  nonceAuthority: Address;
};

export type InitializeNonceAccountInstructionDataArgs = {
  nonceAuthority: Address;
};

export function getInitializeNonceAccountInstructionDataEncoder(): FixedSizeEncoder<InitializeNonceAccountInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ['discriminator', getU32Encoder()],
      ['nonceAuthority', getAddressEncoder()],
    ]),
    (value) => ({
      ...value,
      discriminator: INITIALIZE_NONCE_ACCOUNT_DISCRIMINATOR,
    })
  ) as FixedSizeEncoder<InitializeNonceAccountInstructionDataArgs>;
}

export function getInitializeNonceAccountInstructionDataDecoder(): FixedSizeDecoder<InitializeNonceAccountInstructionData> {
  return getStructDecoder([
    ['discriminator', getU32Decoder()],
    ['nonceAuthority', getAddressDecoder()],
  ]) as FixedSizeDecoder<InitializeNonceAccountInstructionData>;
}

export function getInitializeNonceAccountInstructionDataCodec(): FixedSizeCodec<
  InitializeNonceAccountInstructionDataArgs,
  InitializeNonceAccountInstructionData
> {
  return combineCodec(
    getInitializeNonceAccountInstructionDataEncoder(),
    getInitializeNonceAccountInstructionDataDecoder()
  ) as FixedSizeCodec<
    InitializeNonceAccountInstructionDataArgs,
    InitializeNonceAccountInstructionData
  >;
}

export type InitializeNonceAccountInput<
  TAccountNonceAccount extends string = string,
  TAccountRecentBlockhashesSysvar extends string = string,
  TAccountRentSysvar extends string = string,
> = {
  nonceAccount: Address<TAccountNonceAccount>;
  recentBlockhashesSysvar?: Address<TAccountRecentBlockhashesSysvar>;
  rentSysvar?: Address<TAccountRentSysvar>;
  nonceAuthority: InitializeNonceAccountInstructionDataArgs['nonceAuthority'];
};

export function getInitializeNonceAccountInstruction<
  TAccountNonceAccount extends string,
  TAccountRecentBlockhashesSysvar extends string,
  TAccountRentSysvar extends string,
  TProgramAddress extends Address = typeof SYSTEM_PROGRAM_ADDRESS,
>(
  input: InitializeNonceAccountInput<
    TAccountNonceAccount,
    TAccountRecentBlockhashesSysvar,
    TAccountRentSysvar
  >,
  config?: { programAddress?: TProgramAddress }
): InitializeNonceAccountInstruction<
  TProgramAddress,
  TAccountNonceAccount,
  TAccountRecentBlockhashesSysvar,
  TAccountRentSysvar
> {
  // Program address.
  const programAddress = config?.programAddress ?? SYSTEM_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    nonceAccount: { value: input.nonceAccount ?? null, isWritable: true },
    recentBlockhashesSysvar: {
      value: input.recentBlockhashesSysvar ?? null,
      isWritable: false,
    },
    rentSysvar: { value: input.rentSysvar ?? null, isWritable: false },
  };
  const accounts = originalAccounts as Record<
    keyof typeof originalAccounts,
    ResolvedAccount
  >;

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

  // Resolve default values.
  if (!accounts.recentBlockhashesSysvar.value) {
    accounts.recentBlockhashesSysvar.value =
      'SysvarRecentB1ockHashes11111111111111111111' as Address<'SysvarRecentB1ockHashes11111111111111111111'>;
  }
  if (!accounts.rentSysvar.value) {
    accounts.rentSysvar.value =
      'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>;
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');
  const instruction = {
    accounts: [
      getAccountMeta(accounts.nonceAccount),
      getAccountMeta(accounts.recentBlockhashesSysvar),
      getAccountMeta(accounts.rentSysvar),
    ],
    programAddress,
    data: getInitializeNonceAccountInstructionDataEncoder().encode(
      args as InitializeNonceAccountInstructionDataArgs
    ),
  } as InitializeNonceAccountInstruction<
    TProgramAddress,
    TAccountNonceAccount,
    TAccountRecentBlockhashesSysvar,
    TAccountRentSysvar
  >;

  return instruction;
}

export type ParsedInitializeNonceAccountInstruction<
  TProgram extends string = typeof SYSTEM_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    nonceAccount: TAccountMetas[0];
    recentBlockhashesSysvar: TAccountMetas[1];
    rentSysvar: TAccountMetas[2];
  };
  data: InitializeNonceAccountInstructionData;
};

export function parseInitializeNonceAccountInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>
): ParsedInitializeNonceAccountInstruction<TProgram, TAccountMetas> {
  if (instruction.accounts.length < 3) {
    // 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: {
      nonceAccount: getNextAccount(),
      recentBlockhashesSysvar: getNextAccount(),
      rentSysvar: getNextAccount(),
    },
    data: getInitializeNonceAccountInstructionDataDecoder().decode(
      instruction.data
    ),
  };
}
