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

export const RELAY_ROOT_BUNDLE_DISCRIMINATOR = new Uint8Array([
  69, 13, 223, 204, 251, 61, 105, 6,
]);

export function getRelayRootBundleDiscriminatorBytes() {
  return fixEncoderSize(getBytesEncoder(), 8).encode(
    RELAY_ROOT_BUNDLE_DISCRIMINATOR,
  );
}

export type RelayRootBundleInstruction<
  TProgram extends string = typeof SVM_SPOKE_PROGRAM_ADDRESS,
  TAccountSigner extends string | AccountMeta<string> = string,
  TAccountPayer extends string | AccountMeta<string> = string,
  TAccountState extends string | AccountMeta<string> = string,
  TAccountRootBundle extends string | AccountMeta<string> = string,
  TAccountSystemProgram extends string | AccountMeta<string> =
    "11111111111111111111111111111111",
  TAccountEventAuthority extends string | AccountMeta<string> = string,
  TAccountProgram extends string | AccountMeta<string> = string,
  TRemainingAccounts extends readonly AccountMeta<string>[] = [],
> = Instruction<TProgram> &
  InstructionWithData<ReadonlyUint8Array> &
  InstructionWithAccounts<
    [
      TAccountSigner extends string
        ? ReadonlySignerAccount<TAccountSigner> &
            AccountSignerMeta<TAccountSigner>
        : TAccountSigner,
      TAccountPayer extends string
        ? WritableSignerAccount<TAccountPayer> &
            AccountSignerMeta<TAccountPayer>
        : TAccountPayer,
      TAccountState extends string
        ? WritableAccount<TAccountState>
        : TAccountState,
      TAccountRootBundle extends string
        ? WritableAccount<TAccountRootBundle>
        : TAccountRootBundle,
      TAccountSystemProgram extends string
        ? ReadonlyAccount<TAccountSystemProgram>
        : TAccountSystemProgram,
      TAccountEventAuthority extends string
        ? ReadonlyAccount<TAccountEventAuthority>
        : TAccountEventAuthority,
      TAccountProgram extends string
        ? ReadonlyAccount<TAccountProgram>
        : TAccountProgram,
      ...TRemainingAccounts,
    ]
  >;

export type RelayRootBundleInstructionData = {
  discriminator: ReadonlyUint8Array;
  relayerRefundRoot: ReadonlyUint8Array;
  slowRelayRoot: ReadonlyUint8Array;
};

export type RelayRootBundleInstructionDataArgs = {
  relayerRefundRoot: ReadonlyUint8Array;
  slowRelayRoot: ReadonlyUint8Array;
};

export function getRelayRootBundleInstructionDataEncoder(): FixedSizeEncoder<RelayRootBundleInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", fixEncoderSize(getBytesEncoder(), 8)],
      ["relayerRefundRoot", fixEncoderSize(getBytesEncoder(), 32)],
      ["slowRelayRoot", fixEncoderSize(getBytesEncoder(), 32)],
    ]),
    (value) => ({ ...value, discriminator: RELAY_ROOT_BUNDLE_DISCRIMINATOR }),
  );
}

export function getRelayRootBundleInstructionDataDecoder(): FixedSizeDecoder<RelayRootBundleInstructionData> {
  return getStructDecoder([
    ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
    ["relayerRefundRoot", fixDecoderSize(getBytesDecoder(), 32)],
    ["slowRelayRoot", fixDecoderSize(getBytesDecoder(), 32)],
  ]);
}

export function getRelayRootBundleInstructionDataCodec(): FixedSizeCodec<
  RelayRootBundleInstructionDataArgs,
  RelayRootBundleInstructionData
> {
  return combineCodec(
    getRelayRootBundleInstructionDataEncoder(),
    getRelayRootBundleInstructionDataDecoder(),
  );
}

export type RelayRootBundleAsyncInput<
  TAccountSigner extends string = string,
  TAccountPayer extends string = string,
  TAccountState extends string = string,
  TAccountRootBundle extends string = string,
  TAccountSystemProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  signer: TransactionSigner<TAccountSigner>;
  payer: TransactionSigner<TAccountPayer>;
  state: Address<TAccountState>;
  rootBundle: Address<TAccountRootBundle>;
  systemProgram?: Address<TAccountSystemProgram>;
  eventAuthority?: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  relayerRefundRoot: RelayRootBundleInstructionDataArgs["relayerRefundRoot"];
  slowRelayRoot: RelayRootBundleInstructionDataArgs["slowRelayRoot"];
};

export async function getRelayRootBundleInstructionAsync<
  TAccountSigner extends string,
  TAccountPayer extends string,
  TAccountState extends string,
  TAccountRootBundle extends string,
  TAccountSystemProgram extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address = typeof SVM_SPOKE_PROGRAM_ADDRESS,
>(
  input: RelayRootBundleAsyncInput<
    TAccountSigner,
    TAccountPayer,
    TAccountState,
    TAccountRootBundle,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): Promise<
  RelayRootBundleInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountPayer,
    TAccountState,
    TAccountRootBundle,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >
> {
  // Program address.
  const programAddress = config?.programAddress ?? SVM_SPOKE_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    signer: { value: input.signer ?? null, isWritable: false },
    payer: { value: input.payer ?? null, isWritable: true },
    state: { value: input.state ?? null, isWritable: true },
    rootBundle: { value: input.rootBundle ?? null, isWritable: true },
    systemProgram: { value: input.systemProgram ?? null, isWritable: false },
    eventAuthority: { value: input.eventAuthority ?? null, isWritable: false },
    program: { value: input.program ?? 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">;
  }
  if (!accounts.eventAuthority.value) {
    accounts.eventAuthority.value = await findEventAuthorityPda();
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta(accounts.signer),
      getAccountMeta(accounts.payer),
      getAccountMeta(accounts.state),
      getAccountMeta(accounts.rootBundle),
      getAccountMeta(accounts.systemProgram),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getRelayRootBundleInstructionDataEncoder().encode(
      args as RelayRootBundleInstructionDataArgs,
    ),
    programAddress,
  } as RelayRootBundleInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountPayer,
    TAccountState,
    TAccountRootBundle,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type RelayRootBundleInput<
  TAccountSigner extends string = string,
  TAccountPayer extends string = string,
  TAccountState extends string = string,
  TAccountRootBundle extends string = string,
  TAccountSystemProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  signer: TransactionSigner<TAccountSigner>;
  payer: TransactionSigner<TAccountPayer>;
  state: Address<TAccountState>;
  rootBundle: Address<TAccountRootBundle>;
  systemProgram?: Address<TAccountSystemProgram>;
  eventAuthority: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  relayerRefundRoot: RelayRootBundleInstructionDataArgs["relayerRefundRoot"];
  slowRelayRoot: RelayRootBundleInstructionDataArgs["slowRelayRoot"];
};

export function getRelayRootBundleInstruction<
  TAccountSigner extends string,
  TAccountPayer extends string,
  TAccountState extends string,
  TAccountRootBundle extends string,
  TAccountSystemProgram extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address = typeof SVM_SPOKE_PROGRAM_ADDRESS,
>(
  input: RelayRootBundleInput<
    TAccountSigner,
    TAccountPayer,
    TAccountState,
    TAccountRootBundle,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): RelayRootBundleInstruction<
  TProgramAddress,
  TAccountSigner,
  TAccountPayer,
  TAccountState,
  TAccountRootBundle,
  TAccountSystemProgram,
  TAccountEventAuthority,
  TAccountProgram
> {
  // Program address.
  const programAddress = config?.programAddress ?? SVM_SPOKE_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    signer: { value: input.signer ?? null, isWritable: false },
    payer: { value: input.payer ?? null, isWritable: true },
    state: { value: input.state ?? null, isWritable: true },
    rootBundle: { value: input.rootBundle ?? null, isWritable: true },
    systemProgram: { value: input.systemProgram ?? null, isWritable: false },
    eventAuthority: { value: input.eventAuthority ?? null, isWritable: false },
    program: { value: input.program ?? 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.payer),
      getAccountMeta(accounts.state),
      getAccountMeta(accounts.rootBundle),
      getAccountMeta(accounts.systemProgram),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getRelayRootBundleInstructionDataEncoder().encode(
      args as RelayRootBundleInstructionDataArgs,
    ),
    programAddress,
  } as RelayRootBundleInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountPayer,
    TAccountState,
    TAccountRootBundle,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type ParsedRelayRootBundleInstruction<
  TProgram extends string = typeof SVM_SPOKE_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    signer: TAccountMetas[0];
    payer: TAccountMetas[1];
    state: TAccountMetas[2];
    rootBundle: TAccountMetas[3];
    systemProgram: TAccountMetas[4];
    eventAuthority: TAccountMetas[5];
    program: TAccountMetas[6];
  };
  data: RelayRootBundleInstructionData;
};

export function parseRelayRootBundleInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>,
): ParsedRelayRootBundleInstruction<TProgram, TAccountMetas> {
  if (instruction.accounts.length < 7) {
    // 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(),
      payer: getNextAccount(),
      state: getNextAccount(),
      rootBundle: getNextAccount(),
      systemProgram: getNextAccount(),
      eventAuthority: getNextAccount(),
      program: getNextAccount(),
    },
    data: getRelayRootBundleInstructionDataDecoder().decode(instruction.data),
  };
}
