/**
 * 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 {
  addDecoderSizePrefix,
  addEncoderSizePrefix,
  combineCodec,
  fixDecoderSize,
  fixEncoderSize,
  getBytesDecoder,
  getBytesEncoder,
  getStructDecoder,
  getStructEncoder,
  getU32Decoder,
  getU32Encoder,
  transformEncoder,
  type AccountMeta,
  type AccountSignerMeta,
  type Address,
  type Codec,
  type Decoder,
  type Encoder,
  type Instruction,
  type InstructionWithAccounts,
  type InstructionWithData,
  type ReadonlyAccount,
  type ReadonlySignerAccount,
  type ReadonlyUint8Array,
  type TransactionSigner,
  type WritableAccount,
} from "@solana/kit";
import { findInstructionParamsPda } from "../pdas";
import { SVM_SPOKE_PROGRAM_ADDRESS } from "../programs";
import {
  expectAddress,
  getAccountMetaFactory,
  type ResolvedAccount,
} from "../shared";

export const WRITE_INSTRUCTION_PARAMS_FRAGMENT_DISCRIMINATOR = new Uint8Array([
  238, 182, 109, 113, 124, 255, 72, 18,
]);

export function getWriteInstructionParamsFragmentDiscriminatorBytes() {
  return fixEncoderSize(getBytesEncoder(), 8).encode(
    WRITE_INSTRUCTION_PARAMS_FRAGMENT_DISCRIMINATOR,
  );
}

export type WriteInstructionParamsFragmentInstruction<
  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
        ? ReadonlySignerAccount<TAccountSigner> &
            AccountSignerMeta<TAccountSigner>
        : TAccountSigner,
      TAccountInstructionParams extends string
        ? WritableAccount<TAccountInstructionParams>
        : TAccountInstructionParams,
      TAccountSystemProgram extends string
        ? ReadonlyAccount<TAccountSystemProgram>
        : TAccountSystemProgram,
      ...TRemainingAccounts,
    ]
  >;

export type WriteInstructionParamsFragmentInstructionData = {
  discriminator: ReadonlyUint8Array;
  offset: number;
  fragment: ReadonlyUint8Array;
};

export type WriteInstructionParamsFragmentInstructionDataArgs = {
  offset: number;
  fragment: ReadonlyUint8Array;
};

export function getWriteInstructionParamsFragmentInstructionDataEncoder(): Encoder<WriteInstructionParamsFragmentInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", fixEncoderSize(getBytesEncoder(), 8)],
      ["offset", getU32Encoder()],
      ["fragment", addEncoderSizePrefix(getBytesEncoder(), getU32Encoder())],
    ]),
    (value) => ({
      ...value,
      discriminator: WRITE_INSTRUCTION_PARAMS_FRAGMENT_DISCRIMINATOR,
    }),
  );
}

export function getWriteInstructionParamsFragmentInstructionDataDecoder(): Decoder<WriteInstructionParamsFragmentInstructionData> {
  return getStructDecoder([
    ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
    ["offset", getU32Decoder()],
    ["fragment", addDecoderSizePrefix(getBytesDecoder(), getU32Decoder())],
  ]);
}

export function getWriteInstructionParamsFragmentInstructionDataCodec(): Codec<
  WriteInstructionParamsFragmentInstructionDataArgs,
  WriteInstructionParamsFragmentInstructionData
> {
  return combineCodec(
    getWriteInstructionParamsFragmentInstructionDataEncoder(),
    getWriteInstructionParamsFragmentInstructionDataDecoder(),
  );
}

export type WriteInstructionParamsFragmentAsyncInput<
  TAccountSigner extends string = string,
  TAccountInstructionParams extends string = string,
  TAccountSystemProgram extends string = string,
> = {
  signer: TransactionSigner<TAccountSigner>;
  instructionParams?: Address<TAccountInstructionParams>;
  systemProgram?: Address<TAccountSystemProgram>;
  offset: WriteInstructionParamsFragmentInstructionDataArgs["offset"];
  fragment: WriteInstructionParamsFragmentInstructionDataArgs["fragment"];
};

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

  // Original accounts.
  const originalAccounts = {
    signer: { value: input.signer ?? null, isWritable: false },
    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: getWriteInstructionParamsFragmentInstructionDataEncoder().encode(
      args as WriteInstructionParamsFragmentInstructionDataArgs,
    ),
    programAddress,
  } as WriteInstructionParamsFragmentInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountInstructionParams,
    TAccountSystemProgram
  >);
}

export type WriteInstructionParamsFragmentInput<
  TAccountSigner extends string = string,
  TAccountInstructionParams extends string = string,
  TAccountSystemProgram extends string = string,
> = {
  signer: TransactionSigner<TAccountSigner>;
  instructionParams: Address<TAccountInstructionParams>;
  systemProgram?: Address<TAccountSystemProgram>;
  offset: WriteInstructionParamsFragmentInstructionDataArgs["offset"];
  fragment: WriteInstructionParamsFragmentInstructionDataArgs["fragment"];
};

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

  // Original accounts.
  const originalAccounts = {
    signer: { value: input.signer ?? null, isWritable: false },
    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: getWriteInstructionParamsFragmentInstructionDataEncoder().encode(
      args as WriteInstructionParamsFragmentInstructionDataArgs,
    ),
    programAddress,
  } as WriteInstructionParamsFragmentInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountInstructionParams,
    TAccountSystemProgram
  >);
}

export type ParsedWriteInstructionParamsFragmentInstruction<
  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: WriteInstructionParamsFragmentInstructionData;
};

export function parseWriteInstructionParamsFragmentInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>,
): ParsedWriteInstructionParamsFragmentInstruction<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: getWriteInstructionParamsFragmentInstructionDataDecoder().decode(
      instruction.data,
    ),
  };
}
