/**
 * 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,
  getAddressDecoder,
  getAddressEncoder,
  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 { MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS } from "../programs";
import { getAccountMetaFactory, type ResolvedAccount } from "../shared";

export const SEND_MESSAGE_DISCRIMINATOR = new Uint8Array([
  57, 40, 34, 178, 189, 10, 65, 26,
]);

export function getSendMessageDiscriminatorBytes() {
  return fixEncoderSize(getBytesEncoder(), 8).encode(
    SEND_MESSAGE_DISCRIMINATOR,
  );
}

export type SendMessageInstruction<
  TProgram extends string = typeof MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS,
  TAccountEventRentPayer extends string | AccountMeta<string> = string,
  TAccountSenderAuthorityPda extends string | AccountMeta<string> = string,
  TAccountMessageTransmitter extends string | AccountMeta<string> = string,
  TAccountMessageSentEventData extends string | AccountMeta<string> = string,
  TAccountSenderProgram extends string | AccountMeta<string> = string,
  TAccountSystemProgram extends string | AccountMeta<string> =
    "11111111111111111111111111111111",
  TRemainingAccounts extends readonly AccountMeta<string>[] = [],
> = Instruction<TProgram> &
  InstructionWithData<ReadonlyUint8Array> &
  InstructionWithAccounts<
    [
      TAccountEventRentPayer extends string
        ? WritableSignerAccount<TAccountEventRentPayer> &
            AccountSignerMeta<TAccountEventRentPayer>
        : TAccountEventRentPayer,
      TAccountSenderAuthorityPda extends string
        ? ReadonlySignerAccount<TAccountSenderAuthorityPda> &
            AccountSignerMeta<TAccountSenderAuthorityPda>
        : TAccountSenderAuthorityPda,
      TAccountMessageTransmitter extends string
        ? WritableAccount<TAccountMessageTransmitter>
        : TAccountMessageTransmitter,
      TAccountMessageSentEventData extends string
        ? WritableSignerAccount<TAccountMessageSentEventData> &
            AccountSignerMeta<TAccountMessageSentEventData>
        : TAccountMessageSentEventData,
      TAccountSenderProgram extends string
        ? ReadonlyAccount<TAccountSenderProgram>
        : TAccountSenderProgram,
      TAccountSystemProgram extends string
        ? ReadonlyAccount<TAccountSystemProgram>
        : TAccountSystemProgram,
      ...TRemainingAccounts,
    ]
  >;

export type SendMessageInstructionData = {
  discriminator: ReadonlyUint8Array;
  destinationDomain: number;
  recipient: Address;
  destinationCaller: Address;
  minFinalityThreshold: number;
  messageBody: ReadonlyUint8Array;
};

export type SendMessageInstructionDataArgs = {
  destinationDomain: number;
  recipient: Address;
  destinationCaller: Address;
  minFinalityThreshold: number;
  messageBody: ReadonlyUint8Array;
};

export function getSendMessageInstructionDataEncoder(): Encoder<SendMessageInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", fixEncoderSize(getBytesEncoder(), 8)],
      ["destinationDomain", getU32Encoder()],
      ["recipient", getAddressEncoder()],
      ["destinationCaller", getAddressEncoder()],
      ["minFinalityThreshold", getU32Encoder()],
      ["messageBody", addEncoderSizePrefix(getBytesEncoder(), getU32Encoder())],
    ]),
    (value) => ({ ...value, discriminator: SEND_MESSAGE_DISCRIMINATOR }),
  );
}

export function getSendMessageInstructionDataDecoder(): Decoder<SendMessageInstructionData> {
  return getStructDecoder([
    ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
    ["destinationDomain", getU32Decoder()],
    ["recipient", getAddressDecoder()],
    ["destinationCaller", getAddressDecoder()],
    ["minFinalityThreshold", getU32Decoder()],
    ["messageBody", addDecoderSizePrefix(getBytesDecoder(), getU32Decoder())],
  ]);
}

export function getSendMessageInstructionDataCodec(): Codec<
  SendMessageInstructionDataArgs,
  SendMessageInstructionData
> {
  return combineCodec(
    getSendMessageInstructionDataEncoder(),
    getSendMessageInstructionDataDecoder(),
  );
}

export type SendMessageInput<
  TAccountEventRentPayer extends string = string,
  TAccountSenderAuthorityPda extends string = string,
  TAccountMessageTransmitter extends string = string,
  TAccountMessageSentEventData extends string = string,
  TAccountSenderProgram extends string = string,
  TAccountSystemProgram extends string = string,
> = {
  eventRentPayer: TransactionSigner<TAccountEventRentPayer>;
  senderAuthorityPda: TransactionSigner<TAccountSenderAuthorityPda>;
  messageTransmitter: Address<TAccountMessageTransmitter>;
  messageSentEventData: TransactionSigner<TAccountMessageSentEventData>;
  senderProgram: Address<TAccountSenderProgram>;
  systemProgram?: Address<TAccountSystemProgram>;
  destinationDomain: SendMessageInstructionDataArgs["destinationDomain"];
  recipient: SendMessageInstructionDataArgs["recipient"];
  destinationCaller: SendMessageInstructionDataArgs["destinationCaller"];
  minFinalityThreshold: SendMessageInstructionDataArgs["minFinalityThreshold"];
  messageBody: SendMessageInstructionDataArgs["messageBody"];
};

export function getSendMessageInstruction<
  TAccountEventRentPayer extends string,
  TAccountSenderAuthorityPda extends string,
  TAccountMessageTransmitter extends string,
  TAccountMessageSentEventData extends string,
  TAccountSenderProgram extends string,
  TAccountSystemProgram extends string,
  TProgramAddress extends Address =
    typeof MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS,
>(
  input: SendMessageInput<
    TAccountEventRentPayer,
    TAccountSenderAuthorityPda,
    TAccountMessageTransmitter,
    TAccountMessageSentEventData,
    TAccountSenderProgram,
    TAccountSystemProgram
  >,
  config?: { programAddress?: TProgramAddress },
): SendMessageInstruction<
  TProgramAddress,
  TAccountEventRentPayer,
  TAccountSenderAuthorityPda,
  TAccountMessageTransmitter,
  TAccountMessageSentEventData,
  TAccountSenderProgram,
  TAccountSystemProgram
> {
  // Program address.
  const programAddress =
    config?.programAddress ?? MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    eventRentPayer: { value: input.eventRentPayer ?? null, isWritable: true },
    senderAuthorityPda: {
      value: input.senderAuthorityPda ?? null,
      isWritable: false,
    },
    messageTransmitter: {
      value: input.messageTransmitter ?? null,
      isWritable: true,
    },
    messageSentEventData: {
      value: input.messageSentEventData ?? null,
      isWritable: true,
    },
    senderProgram: { value: input.senderProgram ?? null, isWritable: false },
    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.eventRentPayer),
      getAccountMeta(accounts.senderAuthorityPda),
      getAccountMeta(accounts.messageTransmitter),
      getAccountMeta(accounts.messageSentEventData),
      getAccountMeta(accounts.senderProgram),
      getAccountMeta(accounts.systemProgram),
    ],
    data: getSendMessageInstructionDataEncoder().encode(
      args as SendMessageInstructionDataArgs,
    ),
    programAddress,
  } as SendMessageInstruction<
    TProgramAddress,
    TAccountEventRentPayer,
    TAccountSenderAuthorityPda,
    TAccountMessageTransmitter,
    TAccountMessageSentEventData,
    TAccountSenderProgram,
    TAccountSystemProgram
  >);
}

export type ParsedSendMessageInstruction<
  TProgram extends string = typeof MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    eventRentPayer: TAccountMetas[0];
    senderAuthorityPda: TAccountMetas[1];
    messageTransmitter: TAccountMetas[2];
    messageSentEventData: TAccountMetas[3];
    senderProgram: TAccountMetas[4];
    systemProgram: TAccountMetas[5];
  };
  data: SendMessageInstructionData;
};

export function parseSendMessageInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>,
): ParsedSendMessageInstruction<TProgram, TAccountMetas> {
  if (instruction.accounts.length < 6) {
    // 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: {
      eventRentPayer: getNextAccount(),
      senderAuthorityPda: getNextAccount(),
      messageTransmitter: getNextAccount(),
      messageSentEventData: getNextAccount(),
      senderProgram: getNextAccount(),
      systemProgram: getNextAccount(),
    },
    data: getSendMessageInstructionDataDecoder().decode(instruction.data),
  };
}
