/**
 * 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,
  getU32Decoder,
  getU32Encoder,
  getU64Decoder,
  getU64Encoder,
  transformEncoder,
  type AccountMeta,
  type AccountSignerMeta,
  type Address,
  type FixedSizeCodec,
  type FixedSizeDecoder,
  type FixedSizeEncoder,
  type Instruction,
  type InstructionWithAccounts,
  type InstructionWithData,
  type ReadonlyUint8Array,
  type TransactionSigner,
  type WritableAccount,
  type WritableSignerAccount,
} from '@solana/kit';
import { SYSTEM_PROGRAM_ADDRESS } from '../programs';
import { getAccountMetaFactory, type ResolvedAccount } from '../shared';

export const TRANSFER_SOL_DISCRIMINATOR = 2;

export function getTransferSolDiscriminatorBytes() {
  return getU32Encoder().encode(TRANSFER_SOL_DISCRIMINATOR);
}

export type TransferSolInstruction<
  TProgram extends string = typeof SYSTEM_PROGRAM_ADDRESS,
  TAccountSource extends string | AccountMeta<string> = string,
  TAccountDestination extends string | AccountMeta<string> = string,
  TRemainingAccounts extends readonly AccountMeta<string>[] = [],
> = Instruction<TProgram> &
  InstructionWithData<ReadonlyUint8Array> &
  InstructionWithAccounts<
    [
      TAccountSource extends string
        ? WritableSignerAccount<TAccountSource> &
            AccountSignerMeta<TAccountSource>
        : TAccountSource,
      TAccountDestination extends string
        ? WritableAccount<TAccountDestination>
        : TAccountDestination,
      ...TRemainingAccounts,
    ]
  >;

export type TransferSolInstructionData = {
  discriminator: number;
  amount: bigint;
};

export type TransferSolInstructionDataArgs = { amount: number | bigint };

export function getTransferSolInstructionDataEncoder(): FixedSizeEncoder<TransferSolInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ['discriminator', getU32Encoder()],
      ['amount', getU64Encoder()],
    ]),
    (value) => ({ ...value, discriminator: TRANSFER_SOL_DISCRIMINATOR })
  ) as FixedSizeEncoder<TransferSolInstructionDataArgs>;
}

export function getTransferSolInstructionDataDecoder(): FixedSizeDecoder<TransferSolInstructionData> {
  return getStructDecoder([
    ['discriminator', getU32Decoder()],
    ['amount', getU64Decoder()],
  ]) as FixedSizeDecoder<TransferSolInstructionData>;
}

export function getTransferSolInstructionDataCodec(): FixedSizeCodec<
  TransferSolInstructionDataArgs,
  TransferSolInstructionData
> {
  return combineCodec(
    getTransferSolInstructionDataEncoder(),
    getTransferSolInstructionDataDecoder()
  ) as FixedSizeCodec<
    TransferSolInstructionDataArgs,
    TransferSolInstructionData
  >;
}

export type TransferSolInput<
  TAccountSource extends string = string,
  TAccountDestination extends string = string,
> = {
  source: TransactionSigner<TAccountSource>;
  destination: Address<TAccountDestination>;
  amount: TransferSolInstructionDataArgs['amount'];
};

export function getTransferSolInstruction<
  TAccountSource extends string,
  TAccountDestination extends string,
  TProgramAddress extends Address = typeof SYSTEM_PROGRAM_ADDRESS,
>(
  input: TransferSolInput<TAccountSource, TAccountDestination>,
  config?: { programAddress?: TProgramAddress }
): TransferSolInstruction<
  TProgramAddress,
  TAccountSource,
  TAccountDestination
> {
  // Program address.
  const programAddress = config?.programAddress ?? SYSTEM_PROGRAM_ADDRESS;

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

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

  const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');
  const instruction = {
    accounts: [
      getAccountMeta(accounts.source),
      getAccountMeta(accounts.destination),
    ],
    programAddress,
    data: getTransferSolInstructionDataEncoder().encode(
      args as TransferSolInstructionDataArgs
    ),
  } as TransferSolInstruction<
    TProgramAddress,
    TAccountSource,
    TAccountDestination
  >;

  return instruction;
}

export type ParsedTransferSolInstruction<
  TProgram extends string = typeof SYSTEM_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    source: TAccountMetas[0];
    destination: TAccountMetas[1];
  };
  data: TransferSolInstructionData;
};

export function parseTransferSolInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>
): ParsedTransferSolInstruction<TProgram, TAccountMetas> {
  if (instruction.accounts.length < 2) {
    // 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: {
      source: getNextAccount(),
      destination: getNextAccount(),
    },
    data: getTransferSolInstructionDataDecoder().decode(instruction.data),
  };
}
