/**
 * 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 ReadonlySignerAccount,
  type ReadonlyUint8Array,
  type TransactionSigner,
  type WritableAccount,
  type WritableSignerAccount,
} from "@solana/kit";
import { findEventAuthorityPda, findMessageTransmitterPda } from "../pdas";
import { MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS } from "../programs";
import { 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 MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS,
  TAccountPayer extends string | AccountMeta<string> = string,
  TAccountUpgradeAuthority extends string | AccountMeta<string> = string,
  TAccountMessageTransmitter extends string | AccountMeta<string> = string,
  TAccountMessageTransmitterProgramData extends string | AccountMeta<string> =
    string,
  TAccountMessageTransmitterProgram extends string | AccountMeta<string> =
    "CCTPV2Sm4AdWt5296sk4P66VBZ7bEhcARwFaaS9YPbeC",
  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,
      TAccountUpgradeAuthority extends string
        ? ReadonlySignerAccount<TAccountUpgradeAuthority> &
            AccountSignerMeta<TAccountUpgradeAuthority>
        : TAccountUpgradeAuthority,
      TAccountMessageTransmitter extends string
        ? WritableAccount<TAccountMessageTransmitter>
        : TAccountMessageTransmitter,
      TAccountMessageTransmitterProgramData extends string
        ? ReadonlyAccount<TAccountMessageTransmitterProgramData>
        : TAccountMessageTransmitterProgramData,
      TAccountMessageTransmitterProgram extends string
        ? ReadonlyAccount<TAccountMessageTransmitterProgram>
        : TAccountMessageTransmitterProgram,
      TAccountSystemProgram extends string
        ? ReadonlyAccount<TAccountSystemProgram>
        : TAccountSystemProgram,
      TAccountEventAuthority extends string
        ? ReadonlyAccount<TAccountEventAuthority>
        : TAccountEventAuthority,
      TAccountProgram extends string
        ? ReadonlyAccount<TAccountProgram>
        : TAccountProgram,
      ...TRemainingAccounts,
    ]
  >;

export type InitializeInstructionData = {
  discriminator: ReadonlyUint8Array;
  localDomain: number;
  attester: Address;
  maxMessageBodySize: bigint;
  version: number;
};

export type InitializeInstructionDataArgs = {
  localDomain: number;
  attester: Address;
  maxMessageBodySize: number | bigint;
  version: number;
};

export function getInitializeInstructionDataEncoder(): FixedSizeEncoder<InitializeInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", fixEncoderSize(getBytesEncoder(), 8)],
      ["localDomain", getU32Encoder()],
      ["attester", getAddressEncoder()],
      ["maxMessageBodySize", getU64Encoder()],
      ["version", getU32Encoder()],
    ]),
    (value) => ({ ...value, discriminator: INITIALIZE_DISCRIMINATOR }),
  );
}

export function getInitializeInstructionDataDecoder(): FixedSizeDecoder<InitializeInstructionData> {
  return getStructDecoder([
    ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
    ["localDomain", getU32Decoder()],
    ["attester", getAddressDecoder()],
    ["maxMessageBodySize", getU64Decoder()],
    ["version", getU32Decoder()],
  ]);
}

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

export type InitializeAsyncInput<
  TAccountPayer extends string = string,
  TAccountUpgradeAuthority extends string = string,
  TAccountMessageTransmitter extends string = string,
  TAccountMessageTransmitterProgramData extends string = string,
  TAccountMessageTransmitterProgram extends string = string,
  TAccountSystemProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  payer: TransactionSigner<TAccountPayer>;
  upgradeAuthority: TransactionSigner<TAccountUpgradeAuthority>;
  messageTransmitter?: Address<TAccountMessageTransmitter>;
  messageTransmitterProgramData: Address<TAccountMessageTransmitterProgramData>;
  messageTransmitterProgram?: Address<TAccountMessageTransmitterProgram>;
  systemProgram?: Address<TAccountSystemProgram>;
  eventAuthority?: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  localDomain: InitializeInstructionDataArgs["localDomain"];
  attester: InitializeInstructionDataArgs["attester"];
  maxMessageBodySize: InitializeInstructionDataArgs["maxMessageBodySize"];
  version: InitializeInstructionDataArgs["version"];
};

export async function getInitializeInstructionAsync<
  TAccountPayer extends string,
  TAccountUpgradeAuthority extends string,
  TAccountMessageTransmitter extends string,
  TAccountMessageTransmitterProgramData extends string,
  TAccountMessageTransmitterProgram extends string,
  TAccountSystemProgram extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address =
    typeof MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS,
>(
  input: InitializeAsyncInput<
    TAccountPayer,
    TAccountUpgradeAuthority,
    TAccountMessageTransmitter,
    TAccountMessageTransmitterProgramData,
    TAccountMessageTransmitterProgram,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): Promise<
  InitializeInstruction<
    TProgramAddress,
    TAccountPayer,
    TAccountUpgradeAuthority,
    TAccountMessageTransmitter,
    TAccountMessageTransmitterProgramData,
    TAccountMessageTransmitterProgram,
    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 },
    upgradeAuthority: {
      value: input.upgradeAuthority ?? null,
      isWritable: false,
    },
    messageTransmitter: {
      value: input.messageTransmitter ?? null,
      isWritable: true,
    },
    messageTransmitterProgramData: {
      value: input.messageTransmitterProgramData ?? null,
      isWritable: false,
    },
    messageTransmitterProgram: {
      value: input.messageTransmitterProgram ?? 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.messageTransmitter.value) {
    accounts.messageTransmitter.value = await findMessageTransmitterPda();
  }
  if (!accounts.messageTransmitterProgram.value) {
    accounts.messageTransmitterProgram.value =
      "CCTPV2Sm4AdWt5296sk4P66VBZ7bEhcARwFaaS9YPbeC" as Address<"CCTPV2Sm4AdWt5296sk4P66VBZ7bEhcARwFaaS9YPbeC">;
  }
  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.upgradeAuthority),
      getAccountMeta(accounts.messageTransmitter),
      getAccountMeta(accounts.messageTransmitterProgramData),
      getAccountMeta(accounts.messageTransmitterProgram),
      getAccountMeta(accounts.systemProgram),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getInitializeInstructionDataEncoder().encode(
      args as InitializeInstructionDataArgs,
    ),
    programAddress,
  } as InitializeInstruction<
    TProgramAddress,
    TAccountPayer,
    TAccountUpgradeAuthority,
    TAccountMessageTransmitter,
    TAccountMessageTransmitterProgramData,
    TAccountMessageTransmitterProgram,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type InitializeInput<
  TAccountPayer extends string = string,
  TAccountUpgradeAuthority extends string = string,
  TAccountMessageTransmitter extends string = string,
  TAccountMessageTransmitterProgramData extends string = string,
  TAccountMessageTransmitterProgram extends string = string,
  TAccountSystemProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  payer: TransactionSigner<TAccountPayer>;
  upgradeAuthority: TransactionSigner<TAccountUpgradeAuthority>;
  messageTransmitter: Address<TAccountMessageTransmitter>;
  messageTransmitterProgramData: Address<TAccountMessageTransmitterProgramData>;
  messageTransmitterProgram?: Address<TAccountMessageTransmitterProgram>;
  systemProgram?: Address<TAccountSystemProgram>;
  eventAuthority: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  localDomain: InitializeInstructionDataArgs["localDomain"];
  attester: InitializeInstructionDataArgs["attester"];
  maxMessageBodySize: InitializeInstructionDataArgs["maxMessageBodySize"];
  version: InitializeInstructionDataArgs["version"];
};

export function getInitializeInstruction<
  TAccountPayer extends string,
  TAccountUpgradeAuthority extends string,
  TAccountMessageTransmitter extends string,
  TAccountMessageTransmitterProgramData extends string,
  TAccountMessageTransmitterProgram extends string,
  TAccountSystemProgram extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address =
    typeof MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS,
>(
  input: InitializeInput<
    TAccountPayer,
    TAccountUpgradeAuthority,
    TAccountMessageTransmitter,
    TAccountMessageTransmitterProgramData,
    TAccountMessageTransmitterProgram,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): InitializeInstruction<
  TProgramAddress,
  TAccountPayer,
  TAccountUpgradeAuthority,
  TAccountMessageTransmitter,
  TAccountMessageTransmitterProgramData,
  TAccountMessageTransmitterProgram,
  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 },
    upgradeAuthority: {
      value: input.upgradeAuthority ?? null,
      isWritable: false,
    },
    messageTransmitter: {
      value: input.messageTransmitter ?? null,
      isWritable: true,
    },
    messageTransmitterProgramData: {
      value: input.messageTransmitterProgramData ?? null,
      isWritable: false,
    },
    messageTransmitterProgram: {
      value: input.messageTransmitterProgram ?? 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.messageTransmitterProgram.value) {
    accounts.messageTransmitterProgram.value =
      "CCTPV2Sm4AdWt5296sk4P66VBZ7bEhcARwFaaS9YPbeC" as Address<"CCTPV2Sm4AdWt5296sk4P66VBZ7bEhcARwFaaS9YPbeC">;
  }
  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.upgradeAuthority),
      getAccountMeta(accounts.messageTransmitter),
      getAccountMeta(accounts.messageTransmitterProgramData),
      getAccountMeta(accounts.messageTransmitterProgram),
      getAccountMeta(accounts.systemProgram),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getInitializeInstructionDataEncoder().encode(
      args as InitializeInstructionDataArgs,
    ),
    programAddress,
  } as InitializeInstruction<
    TProgramAddress,
    TAccountPayer,
    TAccountUpgradeAuthority,
    TAccountMessageTransmitter,
    TAccountMessageTransmitterProgramData,
    TAccountMessageTransmitterProgram,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type ParsedInitializeInstruction<
  TProgram extends string = typeof MESSAGE_TRANSMITTER_V2_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    payer: TAccountMetas[0];
    upgradeAuthority: TAccountMetas[1];
    messageTransmitter: TAccountMetas[2];
    messageTransmitterProgramData: TAccountMetas[3];
    messageTransmitterProgram: TAccountMetas[4];
    systemProgram: TAccountMetas[5];
    eventAuthority: TAccountMetas[6];
    program: TAccountMetas[7];
  };
  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 < 8) {
    // 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(),
      upgradeAuthority: getNextAccount(),
      messageTransmitter: getNextAccount(),
      messageTransmitterProgramData: getNextAccount(),
      messageTransmitterProgram: getNextAccount(),
      systemProgram: getNextAccount(),
      eventAuthority: getNextAccount(),
      program: getNextAccount(),
    },
    data: getInitializeInstructionDataDecoder().decode(instruction.data),
  };
}
