/**
 * 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 {
  type Address,
  type IAccountMeta,
  type IInstruction,
  type IInstructionWithAccounts,
  type WritableAccount,
} from '@solana/web3.js';
import { DUMMY_PROGRAM_ADDRESS } from '../programs';
import { getAccountMetaFactory, type ResolvedAccount } from '../shared';

export type Instruction6Instruction<
  TProgram extends string = typeof DUMMY_PROGRAM_ADDRESS,
  TAccountMyAccount extends string | IAccountMeta<string> = string,
  TRemainingAccounts extends readonly IAccountMeta<string>[] = [],
> = IInstruction<TProgram> &
  IInstructionWithAccounts<
    [
      TAccountMyAccount extends string
        ? WritableAccount<TAccountMyAccount>
        : TAccountMyAccount,
      ...TRemainingAccounts,
    ]
  >;

export type Instruction6Input<TAccountMyAccount extends string = string> = {
  myAccount: Address<TAccountMyAccount>;
};

export function getInstruction6Instruction<
  TAccountMyAccount extends string,
  TProgramAddress extends Address = typeof DUMMY_PROGRAM_ADDRESS,
>(
  input: Instruction6Input<TAccountMyAccount>,
  config?: { programAddress?: TProgramAddress }
): Instruction6Instruction<TProgramAddress, TAccountMyAccount> {
  // Program address.
  const programAddress = config?.programAddress ?? DUMMY_PROGRAM_ADDRESS;

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

  const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');
  const instruction = {
    accounts: [getAccountMeta(accounts.myAccount)],
    programAddress,
  } as Instruction6Instruction<TProgramAddress, TAccountMyAccount>;

  return instruction;
}

export type ParsedInstruction6Instruction<
  TProgram extends string = typeof DUMMY_PROGRAM_ADDRESS,
  TAccountMetas extends readonly IAccountMeta[] = readonly IAccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    myAccount: TAccountMetas[0];
  };
};

export function parseInstruction6Instruction<
  TProgram extends string,
  TAccountMetas extends readonly IAccountMeta[],
>(
  instruction: IInstruction<TProgram> & IInstructionWithAccounts<TAccountMetas>
): ParsedInstruction6Instruction<TProgram, TAccountMetas> {
  if (instruction.accounts.length < 1) {
    // 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: {
      myAccount: getNextAccount(),
    },
  };
}
