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

export const INITIALIZE_ACCOUNT_DISCRIMINATOR = 1;

export function getInitializeAccountDiscriminatorBytes() {
  return getU8Encoder().encode(INITIALIZE_ACCOUNT_DISCRIMINATOR);
}

export type InitializeAccountInstruction<
  TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,
  TAccountAccount extends string | AccountMeta<string> = string,
  TAccountMint extends string | AccountMeta<string> = string,
  TAccountOwner extends string | AccountMeta<string> = string,
  TAccountRent extends
    | string
    | AccountMeta<string> = 'SysvarRent111111111111111111111111111111111',
  TRemainingAccounts extends readonly AccountMeta<string>[] = [],
> = Instruction<TProgram> &
  InstructionWithData<ReadonlyUint8Array> &
  InstructionWithAccounts<
    [
      TAccountAccount extends string
        ? WritableAccount<TAccountAccount>
        : TAccountAccount,
      TAccountMint extends string
        ? ReadonlyAccount<TAccountMint>
        : TAccountMint,
      TAccountOwner extends string
        ? ReadonlyAccount<TAccountOwner>
        : TAccountOwner,
      TAccountRent extends string
        ? ReadonlyAccount<TAccountRent>
        : TAccountRent,
      ...TRemainingAccounts,
    ]
  >;

export type InitializeAccountInstructionData = { discriminator: number };

export type InitializeAccountInstructionDataArgs = {};

export function getInitializeAccountInstructionDataEncoder(): FixedSizeEncoder<InitializeAccountInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([['discriminator', getU8Encoder()]]),
    (value) => ({ ...value, discriminator: INITIALIZE_ACCOUNT_DISCRIMINATOR })
  ) as FixedSizeEncoder<InitializeAccountInstructionDataArgs>;
}

export function getInitializeAccountInstructionDataDecoder(): FixedSizeDecoder<InitializeAccountInstructionData> {
  return getStructDecoder([
    ['discriminator', getU8Decoder()],
  ]) as FixedSizeDecoder<InitializeAccountInstructionData>;
}

export function getInitializeAccountInstructionDataCodec(): FixedSizeCodec<
  InitializeAccountInstructionDataArgs,
  InitializeAccountInstructionData
> {
  return combineCodec(
    getInitializeAccountInstructionDataEncoder(),
    getInitializeAccountInstructionDataDecoder()
  ) as FixedSizeCodec<
    InitializeAccountInstructionDataArgs,
    InitializeAccountInstructionData
  >;
}

export type InitializeAccountInput<
  TAccountAccount extends string = string,
  TAccountMint extends string = string,
  TAccountOwner extends string = string,
  TAccountRent extends string = string,
> = {
  /** The account to initialize. */
  account: Address<TAccountAccount>;
  /** The mint this account will be associated with. */
  mint: Address<TAccountMint>;
  /** The new account's owner/multisignature. */
  owner: Address<TAccountOwner>;
  /** Rent sysvar. */
  rent?: Address<TAccountRent>;
};

export function getInitializeAccountInstruction<
  TAccountAccount extends string,
  TAccountMint extends string,
  TAccountOwner extends string,
  TAccountRent extends string,
  TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,
>(
  input: InitializeAccountInput<
    TAccountAccount,
    TAccountMint,
    TAccountOwner,
    TAccountRent
  >,
  config?: { programAddress?: TProgramAddress }
): InitializeAccountInstruction<
  TProgramAddress,
  TAccountAccount,
  TAccountMint,
  TAccountOwner,
  TAccountRent
> {
  // Program address.
  const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;

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

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

  const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');
  const instruction = {
    accounts: [
      getAccountMeta(accounts.account),
      getAccountMeta(accounts.mint),
      getAccountMeta(accounts.owner),
      getAccountMeta(accounts.rent),
    ],
    programAddress,
    data: getInitializeAccountInstructionDataEncoder().encode({}),
  } as InitializeAccountInstruction<
    TProgramAddress,
    TAccountAccount,
    TAccountMint,
    TAccountOwner,
    TAccountRent
  >;

  return instruction;
}

export type ParsedInitializeAccountInstruction<
  TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    /** The account to initialize. */
    account: TAccountMetas[0];
    /** The mint this account will be associated with. */
    mint: TAccountMetas[1];
    /** The new account's owner/multisignature. */
    owner: TAccountMetas[2];
    /** Rent sysvar. */
    rent: TAccountMetas[3];
  };
  data: InitializeAccountInstructionData;
};

export function parseInitializeAccountInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>
): ParsedInitializeAccountInstruction<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: {
      account: getNextAccount(),
      mint: getNextAccount(),
      owner: getNextAccount(),
      rent: getNextAccount(),
    },
    data: getInitializeAccountInstructionDataDecoder().decode(instruction.data),
  };
}
