/**
 * 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,
  type WritableSignerAccount,
} from "@solana/kit";
import { findAuthorityPdaPda, findEventAuthorityPda } from "../pdas";
import { MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS } from "../programs";
import {
  expectAddress,
  getAccountMetaFactory,
  type ResolvedAccount,
} from "../shared";

export const RECEIVE_MESSAGE_DISCRIMINATOR = new Uint8Array([
  38, 144, 127, 225, 31, 225, 238, 25,
]);

export function getReceiveMessageDiscriminatorBytes() {
  return fixEncoderSize(getBytesEncoder(), 8).encode(
    RECEIVE_MESSAGE_DISCRIMINATOR,
  );
}

export type ReceiveMessageInstruction<
  TProgram extends string = typeof MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS,
  TAccountPayer extends string | AccountMeta<string> = string,
  TAccountCaller extends string | AccountMeta<string> = string,
  TAccountAuthorityPda extends string | AccountMeta<string> = string,
  TAccountMessageTransmitter extends string | AccountMeta<string> = string,
  TAccountUsedNonce extends string | AccountMeta<string> = string,
  TAccountReceiver 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<
    [
      TAccountPayer extends string
        ? WritableSignerAccount<TAccountPayer> &
            AccountSignerMeta<TAccountPayer>
        : TAccountPayer,
      TAccountCaller extends string
        ? ReadonlySignerAccount<TAccountCaller> &
            AccountSignerMeta<TAccountCaller>
        : TAccountCaller,
      TAccountAuthorityPda extends string
        ? ReadonlyAccount<TAccountAuthorityPda>
        : TAccountAuthorityPda,
      TAccountMessageTransmitter extends string
        ? ReadonlyAccount<TAccountMessageTransmitter>
        : TAccountMessageTransmitter,
      TAccountUsedNonce extends string
        ? WritableAccount<TAccountUsedNonce>
        : TAccountUsedNonce,
      TAccountReceiver extends string
        ? ReadonlyAccount<TAccountReceiver>
        : TAccountReceiver,
      TAccountSystemProgram extends string
        ? ReadonlyAccount<TAccountSystemProgram>
        : TAccountSystemProgram,
      TAccountEventAuthority extends string
        ? ReadonlyAccount<TAccountEventAuthority>
        : TAccountEventAuthority,
      TAccountProgram extends string
        ? ReadonlyAccount<TAccountProgram>
        : TAccountProgram,
      ...TRemainingAccounts,
    ]
  >;

export type ReceiveMessageInstructionData = {
  discriminator: ReadonlyUint8Array;
  message: ReadonlyUint8Array;
  attestation: ReadonlyUint8Array;
};

export type ReceiveMessageInstructionDataArgs = {
  message: ReadonlyUint8Array;
  attestation: ReadonlyUint8Array;
};

export function getReceiveMessageInstructionDataEncoder(): Encoder<ReceiveMessageInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", fixEncoderSize(getBytesEncoder(), 8)],
      ["message", addEncoderSizePrefix(getBytesEncoder(), getU32Encoder())],
      ["attestation", addEncoderSizePrefix(getBytesEncoder(), getU32Encoder())],
    ]),
    (value) => ({ ...value, discriminator: RECEIVE_MESSAGE_DISCRIMINATOR }),
  );
}

export function getReceiveMessageInstructionDataDecoder(): Decoder<ReceiveMessageInstructionData> {
  return getStructDecoder([
    ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
    ["message", addDecoderSizePrefix(getBytesDecoder(), getU32Decoder())],
    ["attestation", addDecoderSizePrefix(getBytesDecoder(), getU32Decoder())],
  ]);
}

export function getReceiveMessageInstructionDataCodec(): Codec<
  ReceiveMessageInstructionDataArgs,
  ReceiveMessageInstructionData
> {
  return combineCodec(
    getReceiveMessageInstructionDataEncoder(),
    getReceiveMessageInstructionDataDecoder(),
  );
}

export type ReceiveMessageAsyncInput<
  TAccountPayer extends string = string,
  TAccountCaller extends string = string,
  TAccountAuthorityPda extends string = string,
  TAccountMessageTransmitter extends string = string,
  TAccountUsedNonce extends string = string,
  TAccountReceiver extends string = string,
  TAccountSystemProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  payer: TransactionSigner<TAccountPayer>;
  caller: TransactionSigner<TAccountCaller>;
  authorityPda?: Address<TAccountAuthorityPda>;
  messageTransmitter: Address<TAccountMessageTransmitter>;
  /** Each nonce is stored in a separate PDA */
  usedNonce: Address<TAccountUsedNonce>;
  receiver: Address<TAccountReceiver>;
  systemProgram?: Address<TAccountSystemProgram>;
  eventAuthority?: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  message: ReceiveMessageInstructionDataArgs["message"];
  attestation: ReceiveMessageInstructionDataArgs["attestation"];
};

export async function getReceiveMessageInstructionAsync<
  TAccountPayer extends string,
  TAccountCaller extends string,
  TAccountAuthorityPda extends string,
  TAccountMessageTransmitter extends string,
  TAccountUsedNonce extends string,
  TAccountReceiver extends string,
  TAccountSystemProgram extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address =
    typeof MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS,
>(
  input: ReceiveMessageAsyncInput<
    TAccountPayer,
    TAccountCaller,
    TAccountAuthorityPda,
    TAccountMessageTransmitter,
    TAccountUsedNonce,
    TAccountReceiver,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): Promise<
  ReceiveMessageInstruction<
    TProgramAddress,
    TAccountPayer,
    TAccountCaller,
    TAccountAuthorityPda,
    TAccountMessageTransmitter,
    TAccountUsedNonce,
    TAccountReceiver,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >
> {
  // Program address.
  const programAddress =
    config?.programAddress ?? MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    payer: { value: input.payer ?? null, isWritable: true },
    caller: { value: input.caller ?? null, isWritable: false },
    authorityPda: { value: input.authorityPda ?? null, isWritable: false },
    messageTransmitter: {
      value: input.messageTransmitter ?? null,
      isWritable: false,
    },
    usedNonce: { value: input.usedNonce ?? null, isWritable: true },
    receiver: { value: input.receiver ?? null, isWritable: false },
    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.authorityPda.value) {
    accounts.authorityPda.value = await findAuthorityPdaPda({
      receiver: expectAddress(accounts.receiver.value),
    });
  }
  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.payer),
      getAccountMeta(accounts.caller),
      getAccountMeta(accounts.authorityPda),
      getAccountMeta(accounts.messageTransmitter),
      getAccountMeta(accounts.usedNonce),
      getAccountMeta(accounts.receiver),
      getAccountMeta(accounts.systemProgram),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getReceiveMessageInstructionDataEncoder().encode(
      args as ReceiveMessageInstructionDataArgs,
    ),
    programAddress,
  } as ReceiveMessageInstruction<
    TProgramAddress,
    TAccountPayer,
    TAccountCaller,
    TAccountAuthorityPda,
    TAccountMessageTransmitter,
    TAccountUsedNonce,
    TAccountReceiver,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type ReceiveMessageInput<
  TAccountPayer extends string = string,
  TAccountCaller extends string = string,
  TAccountAuthorityPda extends string = string,
  TAccountMessageTransmitter extends string = string,
  TAccountUsedNonce extends string = string,
  TAccountReceiver extends string = string,
  TAccountSystemProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  payer: TransactionSigner<TAccountPayer>;
  caller: TransactionSigner<TAccountCaller>;
  authorityPda: Address<TAccountAuthorityPda>;
  messageTransmitter: Address<TAccountMessageTransmitter>;
  /** Each nonce is stored in a separate PDA */
  usedNonce: Address<TAccountUsedNonce>;
  receiver: Address<TAccountReceiver>;
  systemProgram?: Address<TAccountSystemProgram>;
  eventAuthority: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  message: ReceiveMessageInstructionDataArgs["message"];
  attestation: ReceiveMessageInstructionDataArgs["attestation"];
};

export function getReceiveMessageInstruction<
  TAccountPayer extends string,
  TAccountCaller extends string,
  TAccountAuthorityPda extends string,
  TAccountMessageTransmitter extends string,
  TAccountUsedNonce extends string,
  TAccountReceiver extends string,
  TAccountSystemProgram extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address =
    typeof MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS,
>(
  input: ReceiveMessageInput<
    TAccountPayer,
    TAccountCaller,
    TAccountAuthorityPda,
    TAccountMessageTransmitter,
    TAccountUsedNonce,
    TAccountReceiver,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): ReceiveMessageInstruction<
  TProgramAddress,
  TAccountPayer,
  TAccountCaller,
  TAccountAuthorityPda,
  TAccountMessageTransmitter,
  TAccountUsedNonce,
  TAccountReceiver,
  TAccountSystemProgram,
  TAccountEventAuthority,
  TAccountProgram
> {
  // Program address.
  const programAddress =
    config?.programAddress ?? MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    payer: { value: input.payer ?? null, isWritable: true },
    caller: { value: input.caller ?? null, isWritable: false },
    authorityPda: { value: input.authorityPda ?? null, isWritable: false },
    messageTransmitter: {
      value: input.messageTransmitter ?? null,
      isWritable: false,
    },
    usedNonce: { value: input.usedNonce ?? null, isWritable: true },
    receiver: { value: input.receiver ?? null, isWritable: false },
    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.payer),
      getAccountMeta(accounts.caller),
      getAccountMeta(accounts.authorityPda),
      getAccountMeta(accounts.messageTransmitter),
      getAccountMeta(accounts.usedNonce),
      getAccountMeta(accounts.receiver),
      getAccountMeta(accounts.systemProgram),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getReceiveMessageInstructionDataEncoder().encode(
      args as ReceiveMessageInstructionDataArgs,
    ),
    programAddress,
  } as ReceiveMessageInstruction<
    TProgramAddress,
    TAccountPayer,
    TAccountCaller,
    TAccountAuthorityPda,
    TAccountMessageTransmitter,
    TAccountUsedNonce,
    TAccountReceiver,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type ParsedReceiveMessageInstruction<
  TProgram extends string = typeof MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    payer: TAccountMetas[0];
    caller: TAccountMetas[1];
    authorityPda: TAccountMetas[2];
    messageTransmitter: TAccountMetas[3];
    /** Each nonce is stored in a separate PDA */
    usedNonce: TAccountMetas[4];
    receiver: TAccountMetas[5];
    systemProgram: TAccountMetas[6];
    eventAuthority: TAccountMetas[7];
    program: TAccountMetas[8];
  };
  data: ReceiveMessageInstructionData;
};

export function parseReceiveMessageInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>,
): ParsedReceiveMessageInstruction<TProgram, TAccountMetas> {
  if (instruction.accounts.length < 9) {
    // 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: {
      payer: getNextAccount(),
      caller: getNextAccount(),
      authorityPda: getNextAccount(),
      messageTransmitter: getNextAccount(),
      usedNonce: getNextAccount(),
      receiver: getNextAccount(),
      systemProgram: getNextAccount(),
      eventAuthority: getNextAccount(),
      program: getNextAccount(),
    },
    data: getReceiveMessageInstructionDataDecoder().decode(instruction.data),
  };
}
