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

export const INITIALIZE_INSTRUCTION_PARAMS_DISCRIMINATOR = new Uint8Array([
  94, 206, 190, 192, 127, 8, 186, 28,
]);

export function getInitializeInstructionParamsDiscriminatorBytes() {
  return fixEncoderSize(getBytesEncoder(), 8).encode(
    INITIALIZE_INSTRUCTION_PARAMS_DISCRIMINATOR,
  );
}

export type InitializeInstructionParamsInstruction<
  TProgram extends string = typeof SVM_SPOKE_PROGRAM_ADDRESS,
  TAccountSigner extends string | AccountMeta<string> = string,
  TAccountInstructionParams extends string | AccountMeta<string> = string,
  TAccountSystemProgram extends string | AccountMeta<string> =
    "11111111111111111111111111111111",
  TRemainingAccounts extends readonly AccountMeta<string>[] = [],
> = Instruction<TProgram> &
  InstructionWithData<ReadonlyUint8Array> &
  InstructionWithAccounts<
    [
      TAccountSigner extends string
        ? WritableSignerAccount<TAccountSigner> &
            AccountSignerMeta<TAccountSigner>
        : TAccountSigner,
      TAccountInstructionParams extends string
        ? WritableAccount<TAccountInstructionParams>
        : TAccountInstructionParams,
      TAccountSystemProgram extends string
        ? ReadonlyAccount<TAccountSystemProgram>
        : TAccountSystemProgram,
      ...TRemainingAccounts,
    ]
  >;

export type InitializeInstructionParamsInstructionData = {
  discriminator: ReadonlyUint8Array;
  totalSize: number;
};

export type InitializeInstructionParamsInstructionDataArgs = {
  totalSize: number;
};

export function getInitializeInstructionParamsInstructionDataEncoder(): FixedSizeEncoder<InitializeInstructionParamsInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", fixEncoderSize(getBytesEncoder(), 8)],
      ["totalSize", getU32Encoder()],
    ]),
    (value) => ({
      ...value,
      discriminator: INITIALIZE_INSTRUCTION_PARAMS_DISCRIMINATOR,
    }),
  );
}

export function getInitializeInstructionParamsInstructionDataDecoder(): FixedSizeDecoder<InitializeInstructionParamsInstructionData> {
  return getStructDecoder([
    ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
    ["totalSize", getU32Decoder()],
  ]);
}

export function getInitializeInstructionParamsInstructionDataCodec(): FixedSizeCodec<
  InitializeInstructionParamsInstructionDataArgs,
  InitializeInstructionParamsInstructionData
> {
  return combineCodec(
    getInitializeInstructionParamsInstructionDataEncoder(),
    getInitializeInstructionParamsInstructionDataDecoder(),
  );
}

export type InitializeInstructionParamsAsyncInput<
  TAccountSigner extends string = string,
  TAccountInstructionParams extends string = string,
  TAccountSystemProgram extends string = string,
> = {
  signer: TransactionSigner<TAccountSigner>;
  instructionParams?: Address<TAccountInstructionParams>;
  systemProgram?: Address<TAccountSystemProgram>;
  totalSize: InitializeInstructionParamsInstructionDataArgs["totalSize"];
};

export async function getInitializeInstructionParamsInstructionAsync<
  TAccountSigner extends string,
  TAccountInstructionParams extends string,
  TAccountSystemProgram extends string,
  TProgramAddress extends Address = typeof SVM_SPOKE_PROGRAM_ADDRESS,
>(
  input: InitializeInstructionParamsAsyncInput<
    TAccountSigner,
    TAccountInstructionParams,
    TAccountSystemProgram
  >,
  config?: { programAddress?: TProgramAddress },
): Promise<
  InitializeInstructionParamsInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountInstructionParams,
    TAccountSystemProgram
  >
> {
  // Program address.
  const programAddress = config?.programAddress ?? SVM_SPOKE_PROGRAM_ADDRESS;

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

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

  // Resolve default values.
  if (!accounts.instructionParams.value) {
    accounts.instructionParams.value = await findInstructionParamsPda({
      signer: expectAddress(accounts.signer.value),
    });
  }
  if (!accounts.systemProgram.value) {
    accounts.systemProgram.value =
      "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">;
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta(accounts.signer),
      getAccountMeta(accounts.instructionParams),
      getAccountMeta(accounts.systemProgram),
    ],
    data: getInitializeInstructionParamsInstructionDataEncoder().encode(
      args as InitializeInstructionParamsInstructionDataArgs,
    ),
    programAddress,
  } as InitializeInstructionParamsInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountInstructionParams,
    TAccountSystemProgram
  >);
}

export type InitializeInstructionParamsInput<
  TAccountSigner extends string = string,
  TAccountInstructionParams extends string = string,
  TAccountSystemProgram extends string = string,
> = {
  signer: TransactionSigner<TAccountSigner>;
  instructionParams: Address<TAccountInstructionParams>;
  systemProgram?: Address<TAccountSystemProgram>;
  totalSize: InitializeInstructionParamsInstructionDataArgs["totalSize"];
};

export function getInitializeInstructionParamsInstruction<
  TAccountSigner extends string,
  TAccountInstructionParams extends string,
  TAccountSystemProgram extends string,
  TProgramAddress extends Address = typeof SVM_SPOKE_PROGRAM_ADDRESS,
>(
  input: InitializeInstructionParamsInput<
    TAccountSigner,
    TAccountInstructionParams,
    TAccountSystemProgram
  >,
  config?: { programAddress?: TProgramAddress },
): InitializeInstructionParamsInstruction<
  TProgramAddress,
  TAccountSigner,
  TAccountInstructionParams,
  TAccountSystemProgram
> {
  // Program address.
  const programAddress = config?.programAddress ?? SVM_SPOKE_PROGRAM_ADDRESS;

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

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

  // Resolve default values.
  if (!accounts.systemProgram.value) {
    accounts.systemProgram.value =
      "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">;
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta(accounts.signer),
      getAccountMeta(accounts.instructionParams),
      getAccountMeta(accounts.systemProgram),
    ],
    data: getInitializeInstructionParamsInstructionDataEncoder().encode(
      args as InitializeInstructionParamsInstructionDataArgs,
    ),
    programAddress,
  } as InitializeInstructionParamsInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountInstructionParams,
    TAccountSystemProgram
  >);
}

export type ParsedInitializeInstructionParamsInstruction<
  TProgram extends string = typeof SVM_SPOKE_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    signer: TAccountMetas[0];
    instructionParams: TAccountMetas[1];
    systemProgram: TAccountMetas[2];
  };
  data: InitializeInstructionParamsInstructionData;
};

export function parseInitializeInstructionParamsInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>,
): ParsedInitializeInstructionParamsInstruction<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 as TAccountMetas)[accountIndex]!;
    accountIndex += 1;
    return accountMeta;
  };
  return {
    programAddress: instruction.programAddress,
    accounts: {
      signer: getNextAccount(),
      instructionParams: getNextAccount(),
      systemProgram: getNextAccount(),
    },
    data: getInitializeInstructionParamsInstructionDataDecoder().decode(
      instruction.data,
    ),
  };
}
