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

export const REPLACE_MESSAGE_DISCRIMINATOR = new Uint8Array([
  189, 189, 210, 163, 149, 205, 69, 229,
]);

export function getReplaceMessageDiscriminatorBytes() {
  return fixEncoderSize(getBytesEncoder(), 8).encode(
    REPLACE_MESSAGE_DISCRIMINATOR,
  );
}

export type ReplaceMessageInstruction<
  TProgram extends string = typeof MESSAGE_TRANSMITTER_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 ReplaceMessageInstructionData = {
  discriminator: ReadonlyUint8Array;
  originalMessage: ReadonlyUint8Array;
  originalAttestation: ReadonlyUint8Array;
  newMessageBody: ReadonlyUint8Array;
  newDestinationCaller: Address;
};

export type ReplaceMessageInstructionDataArgs = {
  originalMessage: ReadonlyUint8Array;
  originalAttestation: ReadonlyUint8Array;
  newMessageBody: ReadonlyUint8Array;
  newDestinationCaller: Address;
};

export function getReplaceMessageInstructionDataEncoder(): Encoder<ReplaceMessageInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", fixEncoderSize(getBytesEncoder(), 8)],
      [
        "originalMessage",
        addEncoderSizePrefix(getBytesEncoder(), getU32Encoder()),
      ],
      [
        "originalAttestation",
        addEncoderSizePrefix(getBytesEncoder(), getU32Encoder()),
      ],
      [
        "newMessageBody",
        addEncoderSizePrefix(getBytesEncoder(), getU32Encoder()),
      ],
      ["newDestinationCaller", getAddressEncoder()],
    ]),
    (value) => ({ ...value, discriminator: REPLACE_MESSAGE_DISCRIMINATOR }),
  );
}

export function getReplaceMessageInstructionDataDecoder(): Decoder<ReplaceMessageInstructionData> {
  return getStructDecoder([
    ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
    [
      "originalMessage",
      addDecoderSizePrefix(getBytesDecoder(), getU32Decoder()),
    ],
    [
      "originalAttestation",
      addDecoderSizePrefix(getBytesDecoder(), getU32Decoder()),
    ],
    [
      "newMessageBody",
      addDecoderSizePrefix(getBytesDecoder(), getU32Decoder()),
    ],
    ["newDestinationCaller", getAddressDecoder()],
  ]);
}

export function getReplaceMessageInstructionDataCodec(): Codec<
  ReplaceMessageInstructionDataArgs,
  ReplaceMessageInstructionData
> {
  return combineCodec(
    getReplaceMessageInstructionDataEncoder(),
    getReplaceMessageInstructionDataDecoder(),
  );
}

export type ReplaceMessageInput<
  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>;
  originalMessage: ReplaceMessageInstructionDataArgs["originalMessage"];
  originalAttestation: ReplaceMessageInstructionDataArgs["originalAttestation"];
  newMessageBody: ReplaceMessageInstructionDataArgs["newMessageBody"];
  newDestinationCaller: ReplaceMessageInstructionDataArgs["newDestinationCaller"];
};

export function getReplaceMessageInstruction<
  TAccountEventRentPayer extends string,
  TAccountSenderAuthorityPda extends string,
  TAccountMessageTransmitter extends string,
  TAccountMessageSentEventData extends string,
  TAccountSenderProgram extends string,
  TAccountSystemProgram extends string,
  TProgramAddress extends Address = typeof MESSAGE_TRANSMITTER_PROGRAM_ADDRESS,
>(
  input: ReplaceMessageInput<
    TAccountEventRentPayer,
    TAccountSenderAuthorityPda,
    TAccountMessageTransmitter,
    TAccountMessageSentEventData,
    TAccountSenderProgram,
    TAccountSystemProgram
  >,
  config?: { programAddress?: TProgramAddress },
): ReplaceMessageInstruction<
  TProgramAddress,
  TAccountEventRentPayer,
  TAccountSenderAuthorityPda,
  TAccountMessageTransmitter,
  TAccountMessageSentEventData,
  TAccountSenderProgram,
  TAccountSystemProgram
> {
  // Program address.
  const programAddress =
    config?.programAddress ?? MESSAGE_TRANSMITTER_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: getReplaceMessageInstructionDataEncoder().encode(
      args as ReplaceMessageInstructionDataArgs,
    ),
    programAddress,
  } as ReplaceMessageInstruction<
    TProgramAddress,
    TAccountEventRentPayer,
    TAccountSenderAuthorityPda,
    TAccountMessageTransmitter,
    TAccountMessageSentEventData,
    TAccountSenderProgram,
    TAccountSystemProgram
  >);
}

export type ParsedReplaceMessageInstruction<
  TProgram extends string = typeof MESSAGE_TRANSMITTER_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: ReplaceMessageInstructionData;
};

export function parseReplaceMessageInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>,
): ParsedReplaceMessageInstruction<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: getReplaceMessageInstructionDataDecoder().decode(instruction.data),
  };
}
