/**
 * 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,
  getAddressDecoder,
  getAddressEncoder,
  getBytesDecoder,
  getBytesEncoder,
  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 ReadonlyAccount,
  type ReadonlyUint8Array,
  type TransactionSigner,
  type WritableAccount,
  type WritableSignerAccount,
} from "@solana/kit";
import { findStatePda } from "../pdas";
import { SVM_SPOKE_PROGRAM_ADDRESS } from "../programs";
import {
  expectSome,
  getAccountMetaFactory,
  type ResolvedAccount,
} from "../shared";

export const INITIALIZE_DISCRIMINATOR = new Uint8Array([
  175, 175, 109, 31, 13, 152, 155, 237,
]);

export function getInitializeDiscriminatorBytes() {
  return fixEncoderSize(getBytesEncoder(), 8).encode(INITIALIZE_DISCRIMINATOR);
}

export type InitializeInstruction<
  TProgram extends string = typeof SVM_SPOKE_PROGRAM_ADDRESS,
  TAccountSigner extends string | AccountMeta<string> = string,
  TAccountState 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,
      TAccountState extends string
        ? WritableAccount<TAccountState>
        : TAccountState,
      TAccountSystemProgram extends string
        ? ReadonlyAccount<TAccountSystemProgram>
        : TAccountSystemProgram,
      ...TRemainingAccounts,
    ]
  >;

export type InitializeInstructionData = {
  discriminator: ReadonlyUint8Array;
  seed: bigint;
  initialNumberOfDeposits: number;
  chainId: bigint;
  remoteDomain: number;
  crossDomainAdmin: Address;
  depositQuoteTimeBuffer: number;
  fillDeadlineBuffer: number;
};

export type InitializeInstructionDataArgs = {
  seed: number | bigint;
  initialNumberOfDeposits: number;
  chainId: number | bigint;
  remoteDomain: number;
  crossDomainAdmin: Address;
  depositQuoteTimeBuffer: number;
  fillDeadlineBuffer: number;
};

export function getInitializeInstructionDataEncoder(): FixedSizeEncoder<InitializeInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", fixEncoderSize(getBytesEncoder(), 8)],
      ["seed", getU64Encoder()],
      ["initialNumberOfDeposits", getU32Encoder()],
      ["chainId", getU64Encoder()],
      ["remoteDomain", getU32Encoder()],
      ["crossDomainAdmin", getAddressEncoder()],
      ["depositQuoteTimeBuffer", getU32Encoder()],
      ["fillDeadlineBuffer", getU32Encoder()],
    ]),
    (value) => ({ ...value, discriminator: INITIALIZE_DISCRIMINATOR }),
  );
}

export function getInitializeInstructionDataDecoder(): FixedSizeDecoder<InitializeInstructionData> {
  return getStructDecoder([
    ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
    ["seed", getU64Decoder()],
    ["initialNumberOfDeposits", getU32Decoder()],
    ["chainId", getU64Decoder()],
    ["remoteDomain", getU32Decoder()],
    ["crossDomainAdmin", getAddressDecoder()],
    ["depositQuoteTimeBuffer", getU32Decoder()],
    ["fillDeadlineBuffer", getU32Decoder()],
  ]);
}

export function getInitializeInstructionDataCodec(): FixedSizeCodec<
  InitializeInstructionDataArgs,
  InitializeInstructionData
> {
  return combineCodec(
    getInitializeInstructionDataEncoder(),
    getInitializeInstructionDataDecoder(),
  );
}

export type InitializeAsyncInput<
  TAccountSigner extends string = string,
  TAccountState extends string = string,
  TAccountSystemProgram extends string = string,
> = {
  signer: TransactionSigner<TAccountSigner>;
  state?: Address<TAccountState>;
  systemProgram?: Address<TAccountSystemProgram>;
  seed: InitializeInstructionDataArgs["seed"];
  initialNumberOfDeposits: InitializeInstructionDataArgs["initialNumberOfDeposits"];
  chainId: InitializeInstructionDataArgs["chainId"];
  remoteDomain: InitializeInstructionDataArgs["remoteDomain"];
  crossDomainAdmin: InitializeInstructionDataArgs["crossDomainAdmin"];
  depositQuoteTimeBuffer: InitializeInstructionDataArgs["depositQuoteTimeBuffer"];
  fillDeadlineBuffer: InitializeInstructionDataArgs["fillDeadlineBuffer"];
};

export async function getInitializeInstructionAsync<
  TAccountSigner extends string,
  TAccountState extends string,
  TAccountSystemProgram extends string,
  TProgramAddress extends Address = typeof SVM_SPOKE_PROGRAM_ADDRESS,
>(
  input: InitializeAsyncInput<
    TAccountSigner,
    TAccountState,
    TAccountSystemProgram
  >,
  config?: { programAddress?: TProgramAddress },
): Promise<
  InitializeInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountState,
    TAccountSystemProgram
  >
> {
  // Program address.
  const programAddress = config?.programAddress ?? SVM_SPOKE_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    signer: { value: input.signer ?? null, isWritable: true },
    state: { value: input.state ?? 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.state.value) {
    accounts.state.value = await findStatePda({ seed: expectSome(args.seed) });
  }
  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.state),
      getAccountMeta(accounts.systemProgram),
    ],
    data: getInitializeInstructionDataEncoder().encode(
      args as InitializeInstructionDataArgs,
    ),
    programAddress,
  } as InitializeInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountState,
    TAccountSystemProgram
  >);
}

export type InitializeInput<
  TAccountSigner extends string = string,
  TAccountState extends string = string,
  TAccountSystemProgram extends string = string,
> = {
  signer: TransactionSigner<TAccountSigner>;
  state: Address<TAccountState>;
  systemProgram?: Address<TAccountSystemProgram>;
  seed: InitializeInstructionDataArgs["seed"];
  initialNumberOfDeposits: InitializeInstructionDataArgs["initialNumberOfDeposits"];
  chainId: InitializeInstructionDataArgs["chainId"];
  remoteDomain: InitializeInstructionDataArgs["remoteDomain"];
  crossDomainAdmin: InitializeInstructionDataArgs["crossDomainAdmin"];
  depositQuoteTimeBuffer: InitializeInstructionDataArgs["depositQuoteTimeBuffer"];
  fillDeadlineBuffer: InitializeInstructionDataArgs["fillDeadlineBuffer"];
};

export function getInitializeInstruction<
  TAccountSigner extends string,
  TAccountState extends string,
  TAccountSystemProgram extends string,
  TProgramAddress extends Address = typeof SVM_SPOKE_PROGRAM_ADDRESS,
>(
  input: InitializeInput<TAccountSigner, TAccountState, TAccountSystemProgram>,
  config?: { programAddress?: TProgramAddress },
): InitializeInstruction<
  TProgramAddress,
  TAccountSigner,
  TAccountState,
  TAccountSystemProgram
> {
  // Program address.
  const programAddress = config?.programAddress ?? SVM_SPOKE_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    signer: { value: input.signer ?? null, isWritable: true },
    state: { value: input.state ?? 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.state),
      getAccountMeta(accounts.systemProgram),
    ],
    data: getInitializeInstructionDataEncoder().encode(
      args as InitializeInstructionDataArgs,
    ),
    programAddress,
  } as InitializeInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountState,
    TAccountSystemProgram
  >);
}

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

export function parseInitializeInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>,
): ParsedInitializeInstruction<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(),
      state: getNextAccount(),
      systemProgram: getNextAccount(),
    },
    data: getInitializeInstructionDataDecoder().decode(instruction.data),
  };
}
