/**
 * 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,
  getOptionDecoder,
  getOptionEncoder,
  getStructDecoder,
  getStructEncoder,
  transformEncoder,
  type AccountMeta,
  type AccountSignerMeta,
  type Address,
  type Codec,
  type Decoder,
  type Encoder,
  type Instruction,
  type InstructionWithAccounts,
  type InstructionWithData,
  type Option,
  type OptionOrNullable,
  type ReadonlyAccount,
  type ReadonlyUint8Array,
  type TransactionSigner,
  type WritableAccount,
  type WritableSignerAccount,
} from "@solana/kit";
import {
  findEventAuthorityPda,
  findFillStatusPda,
  findInstructionParamsPda,
} from "../pdas";
import { SVM_SPOKE_PROGRAM_ADDRESS } from "../programs";
import {
  expectAddress,
  expectSome,
  getAccountMetaFactory,
  type ResolvedAccount,
} from "../shared";
import {
  getRelayDataDecoder,
  getRelayDataEncoder,
  type RelayData,
  type RelayDataArgs,
} from "../types";

export const REQUEST_SLOW_FILL_DISCRIMINATOR = new Uint8Array([
  39, 157, 165, 187, 88, 217, 207, 98,
]);

export function getRequestSlowFillDiscriminatorBytes() {
  return fixEncoderSize(getBytesEncoder(), 8).encode(
    REQUEST_SLOW_FILL_DISCRIMINATOR,
  );
}

export type RequestSlowFillInstruction<
  TProgram extends string = typeof SVM_SPOKE_PROGRAM_ADDRESS,
  TAccountSigner extends string | AccountMeta<string> = string,
  TAccountInstructionParams extends string | AccountMeta<string> = string,
  TAccountState extends string | AccountMeta<string> = string,
  TAccountFillStatus 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
        ? WritableSignerAccount<TAccountSigner> &
            AccountSignerMeta<TAccountSigner>
        : TAccountSigner,
      TAccountInstructionParams extends string
        ? WritableAccount<TAccountInstructionParams>
        : TAccountInstructionParams,
      TAccountState extends string
        ? ReadonlyAccount<TAccountState>
        : TAccountState,
      TAccountFillStatus extends string
        ? WritableAccount<TAccountFillStatus>
        : TAccountFillStatus,
      TAccountSystemProgram extends string
        ? ReadonlyAccount<TAccountSystemProgram>
        : TAccountSystemProgram,
      TAccountEventAuthority extends string
        ? ReadonlyAccount<TAccountEventAuthority>
        : TAccountEventAuthority,
      TAccountProgram extends string
        ? ReadonlyAccount<TAccountProgram>
        : TAccountProgram,
      ...TRemainingAccounts,
    ]
  >;

export type RequestSlowFillInstructionData = {
  discriminator: ReadonlyUint8Array;
  relayHash: ReadonlyUint8Array;
  relayData: Option<RelayData>;
};

export type RequestSlowFillInstructionDataArgs = {
  relayHash: ReadonlyUint8Array;
  relayData: OptionOrNullable<RelayDataArgs>;
};

export function getRequestSlowFillInstructionDataEncoder(): Encoder<RequestSlowFillInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", fixEncoderSize(getBytesEncoder(), 8)],
      ["relayHash", fixEncoderSize(getBytesEncoder(), 32)],
      ["relayData", getOptionEncoder(getRelayDataEncoder())],
    ]),
    (value) => ({ ...value, discriminator: REQUEST_SLOW_FILL_DISCRIMINATOR }),
  );
}

export function getRequestSlowFillInstructionDataDecoder(): Decoder<RequestSlowFillInstructionData> {
  return getStructDecoder([
    ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
    ["relayHash", fixDecoderSize(getBytesDecoder(), 32)],
    ["relayData", getOptionDecoder(getRelayDataDecoder())],
  ]);
}

export function getRequestSlowFillInstructionDataCodec(): Codec<
  RequestSlowFillInstructionDataArgs,
  RequestSlowFillInstructionData
> {
  return combineCodec(
    getRequestSlowFillInstructionDataEncoder(),
    getRequestSlowFillInstructionDataDecoder(),
  );
}

export type RequestSlowFillAsyncInput<
  TAccountSigner extends string = string,
  TAccountInstructionParams extends string = string,
  TAccountState extends string = string,
  TAccountFillStatus extends string = string,
  TAccountSystemProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  signer: TransactionSigner<TAccountSigner>;
  instructionParams?: Address<TAccountInstructionParams>;
  state: Address<TAccountState>;
  fillStatus?: Address<TAccountFillStatus>;
  systemProgram?: Address<TAccountSystemProgram>;
  eventAuthority?: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  relayHash: RequestSlowFillInstructionDataArgs["relayHash"];
  relayData: RequestSlowFillInstructionDataArgs["relayData"];
};

export async function getRequestSlowFillInstructionAsync<
  TAccountSigner extends string,
  TAccountInstructionParams extends string,
  TAccountState extends string,
  TAccountFillStatus extends string,
  TAccountSystemProgram extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address = typeof SVM_SPOKE_PROGRAM_ADDRESS,
>(
  input: RequestSlowFillAsyncInput<
    TAccountSigner,
    TAccountInstructionParams,
    TAccountState,
    TAccountFillStatus,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): Promise<
  RequestSlowFillInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountInstructionParams,
    TAccountState,
    TAccountFillStatus,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >
> {
  // 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,
    },
    state: { value: input.state ?? null, isWritable: false },
    fillStatus: { value: input.fillStatus ?? 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.instructionParams.value) {
    accounts.instructionParams.value = await findInstructionParamsPda({
      signer: expectAddress(accounts.signer.value),
    });
  }
  if (!accounts.fillStatus.value) {
    accounts.fillStatus.value = await findFillStatusPda({
      relayHash: expectSome(args.relayHash),
    });
  }
  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.instructionParams),
      getAccountMeta(accounts.state),
      getAccountMeta(accounts.fillStatus),
      getAccountMeta(accounts.systemProgram),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getRequestSlowFillInstructionDataEncoder().encode(
      args as RequestSlowFillInstructionDataArgs,
    ),
    programAddress,
  } as RequestSlowFillInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountInstructionParams,
    TAccountState,
    TAccountFillStatus,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type RequestSlowFillInput<
  TAccountSigner extends string = string,
  TAccountInstructionParams extends string = string,
  TAccountState extends string = string,
  TAccountFillStatus extends string = string,
  TAccountSystemProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  signer: TransactionSigner<TAccountSigner>;
  instructionParams?: Address<TAccountInstructionParams>;
  state: Address<TAccountState>;
  fillStatus: Address<TAccountFillStatus>;
  systemProgram?: Address<TAccountSystemProgram>;
  eventAuthority: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  relayHash: RequestSlowFillInstructionDataArgs["relayHash"];
  relayData: RequestSlowFillInstructionDataArgs["relayData"];
};

export function getRequestSlowFillInstruction<
  TAccountSigner extends string,
  TAccountInstructionParams extends string,
  TAccountState extends string,
  TAccountFillStatus extends string,
  TAccountSystemProgram extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address = typeof SVM_SPOKE_PROGRAM_ADDRESS,
>(
  input: RequestSlowFillInput<
    TAccountSigner,
    TAccountInstructionParams,
    TAccountState,
    TAccountFillStatus,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): RequestSlowFillInstruction<
  TProgramAddress,
  TAccountSigner,
  TAccountInstructionParams,
  TAccountState,
  TAccountFillStatus,
  TAccountSystemProgram,
  TAccountEventAuthority,
  TAccountProgram
> {
  // 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,
    },
    state: { value: input.state ?? null, isWritable: false },
    fillStatus: { value: input.fillStatus ?? 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.instructionParams),
      getAccountMeta(accounts.state),
      getAccountMeta(accounts.fillStatus),
      getAccountMeta(accounts.systemProgram),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getRequestSlowFillInstructionDataEncoder().encode(
      args as RequestSlowFillInstructionDataArgs,
    ),
    programAddress,
  } as RequestSlowFillInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountInstructionParams,
    TAccountState,
    TAccountFillStatus,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type ParsedRequestSlowFillInstruction<
  TProgram extends string = typeof SVM_SPOKE_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    signer: TAccountMetas[0];
    instructionParams?: TAccountMetas[1] | undefined;
    state: TAccountMetas[2];
    fillStatus: TAccountMetas[3];
    systemProgram: TAccountMetas[4];
    eventAuthority: TAccountMetas[5];
    program: TAccountMetas[6];
  };
  data: RequestSlowFillInstructionData;
};

export function parseRequestSlowFillInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>,
): ParsedRequestSlowFillInstruction<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;
  };
  const getNextOptionalAccount = () => {
    const accountMeta = getNextAccount();
    return accountMeta.address === SVM_SPOKE_PROGRAM_ADDRESS
      ? undefined
      : accountMeta;
  };
  return {
    programAddress: instruction.programAddress,
    accounts: {
      signer: getNextAccount(),
      instructionParams: getNextOptionalAccount(),
      state: getNextAccount(),
      fillStatus: getNextAccount(),
      systemProgram: getNextAccount(),
      eventAuthority: getNextAccount(),
      program: getNextAccount(),
    },
    data: getRequestSlowFillInstructionDataDecoder().decode(instruction.data),
  };
}
