/**
 * 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,
  getProgramDerivedAddress,
  getStructDecoder,
  getStructEncoder,
  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,
} from "@solana/kit";
import { findEventAuthorityPda } from "../pdas";
import { TOKEN_MESSENGER_MINTER_V2_PROGRAM_ADDRESS } from "../programs";
import { getAccountMetaFactory, type ResolvedAccount } from "../shared";
import {
  getHandleReceiveMessageParamsDecoder,
  getHandleReceiveMessageParamsEncoder,
  type HandleReceiveMessageParams,
  type HandleReceiveMessageParamsArgs,
} from "../types";

export const HANDLE_RECEIVE_UNFINALIZED_MESSAGE_DISCRIMINATOR = new Uint8Array([
  200, 169, 175, 20, 200, 58, 182, 61,
]);

export function getHandleReceiveUnfinalizedMessageDiscriminatorBytes() {
  return fixEncoderSize(getBytesEncoder(), 8).encode(
    HANDLE_RECEIVE_UNFINALIZED_MESSAGE_DISCRIMINATOR,
  );
}

export type HandleReceiveUnfinalizedMessageInstruction<
  TProgram extends string = typeof TOKEN_MESSENGER_MINTER_V2_PROGRAM_ADDRESS,
  TAccountAuthorityPda extends string | AccountMeta<string> = string,
  TAccountTokenMessenger extends string | AccountMeta<string> = string,
  TAccountRemoteTokenMessenger extends string | AccountMeta<string> = string,
  TAccountTokenMinter extends string | AccountMeta<string> = string,
  TAccountLocalToken extends string | AccountMeta<string> = string,
  TAccountTokenPair extends string | AccountMeta<string> = string,
  TAccountFeeRecipientTokenAccount extends string | AccountMeta<string> =
    string,
  TAccountRecipientTokenAccount extends string | AccountMeta<string> = string,
  TAccountCustodyTokenAccount extends string | AccountMeta<string> = string,
  TAccountTokenProgram extends string | AccountMeta<string> =
    "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
  TAccountEventAuthority extends string | AccountMeta<string> = string,
  TAccountProgram extends string | AccountMeta<string> = string,
  TRemainingAccounts extends readonly AccountMeta<string>[] = [],
> = Instruction<TProgram> &
  InstructionWithData<ReadonlyUint8Array> &
  InstructionWithAccounts<
    [
      TAccountAuthorityPda extends string
        ? ReadonlySignerAccount<TAccountAuthorityPda> &
            AccountSignerMeta<TAccountAuthorityPda>
        : TAccountAuthorityPda,
      TAccountTokenMessenger extends string
        ? ReadonlyAccount<TAccountTokenMessenger>
        : TAccountTokenMessenger,
      TAccountRemoteTokenMessenger extends string
        ? ReadonlyAccount<TAccountRemoteTokenMessenger>
        : TAccountRemoteTokenMessenger,
      TAccountTokenMinter extends string
        ? ReadonlyAccount<TAccountTokenMinter>
        : TAccountTokenMinter,
      TAccountLocalToken extends string
        ? WritableAccount<TAccountLocalToken>
        : TAccountLocalToken,
      TAccountTokenPair extends string
        ? ReadonlyAccount<TAccountTokenPair>
        : TAccountTokenPair,
      TAccountFeeRecipientTokenAccount extends string
        ? WritableAccount<TAccountFeeRecipientTokenAccount>
        : TAccountFeeRecipientTokenAccount,
      TAccountRecipientTokenAccount extends string
        ? WritableAccount<TAccountRecipientTokenAccount>
        : TAccountRecipientTokenAccount,
      TAccountCustodyTokenAccount extends string
        ? WritableAccount<TAccountCustodyTokenAccount>
        : TAccountCustodyTokenAccount,
      TAccountTokenProgram extends string
        ? ReadonlyAccount<TAccountTokenProgram>
        : TAccountTokenProgram,
      TAccountEventAuthority extends string
        ? ReadonlyAccount<TAccountEventAuthority>
        : TAccountEventAuthority,
      TAccountProgram extends string
        ? ReadonlyAccount<TAccountProgram>
        : TAccountProgram,
      ...TRemainingAccounts,
    ]
  >;

export type HandleReceiveUnfinalizedMessageInstructionData = {
  discriminator: ReadonlyUint8Array;
  params: HandleReceiveMessageParams;
};

export type HandleReceiveUnfinalizedMessageInstructionDataArgs = {
  params: HandleReceiveMessageParamsArgs;
};

export function getHandleReceiveUnfinalizedMessageInstructionDataEncoder(): Encoder<HandleReceiveUnfinalizedMessageInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", fixEncoderSize(getBytesEncoder(), 8)],
      ["params", getHandleReceiveMessageParamsEncoder()],
    ]),
    (value) => ({
      ...value,
      discriminator: HANDLE_RECEIVE_UNFINALIZED_MESSAGE_DISCRIMINATOR,
    }),
  );
}

export function getHandleReceiveUnfinalizedMessageInstructionDataDecoder(): Decoder<HandleReceiveUnfinalizedMessageInstructionData> {
  return getStructDecoder([
    ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
    ["params", getHandleReceiveMessageParamsDecoder()],
  ]);
}

export function getHandleReceiveUnfinalizedMessageInstructionDataCodec(): Codec<
  HandleReceiveUnfinalizedMessageInstructionDataArgs,
  HandleReceiveUnfinalizedMessageInstructionData
> {
  return combineCodec(
    getHandleReceiveUnfinalizedMessageInstructionDataEncoder(),
    getHandleReceiveUnfinalizedMessageInstructionDataDecoder(),
  );
}

export type HandleReceiveUnfinalizedMessageAsyncInput<
  TAccountAuthorityPda extends string = string,
  TAccountTokenMessenger extends string = string,
  TAccountRemoteTokenMessenger extends string = string,
  TAccountTokenMinter extends string = string,
  TAccountLocalToken extends string = string,
  TAccountTokenPair extends string = string,
  TAccountFeeRecipientTokenAccount extends string = string,
  TAccountRecipientTokenAccount extends string = string,
  TAccountCustodyTokenAccount extends string = string,
  TAccountTokenProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  authorityPda?: TransactionSigner<TAccountAuthorityPda>;
  tokenMessenger: Address<TAccountTokenMessenger>;
  remoteTokenMessenger: Address<TAccountRemoteTokenMessenger>;
  tokenMinter: Address<TAccountTokenMinter>;
  localToken: Address<TAccountLocalToken>;
  tokenPair: Address<TAccountTokenPair>;
  feeRecipientTokenAccount: Address<TAccountFeeRecipientTokenAccount>;
  recipientTokenAccount: Address<TAccountRecipientTokenAccount>;
  custodyTokenAccount: Address<TAccountCustodyTokenAccount>;
  tokenProgram?: Address<TAccountTokenProgram>;
  eventAuthority?: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  params: HandleReceiveUnfinalizedMessageInstructionDataArgs["params"];
};

export async function getHandleReceiveUnfinalizedMessageInstructionAsync<
  TAccountAuthorityPda extends string,
  TAccountTokenMessenger extends string,
  TAccountRemoteTokenMessenger extends string,
  TAccountTokenMinter extends string,
  TAccountLocalToken extends string,
  TAccountTokenPair extends string,
  TAccountFeeRecipientTokenAccount extends string,
  TAccountRecipientTokenAccount extends string,
  TAccountCustodyTokenAccount extends string,
  TAccountTokenProgram extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address =
    typeof TOKEN_MESSENGER_MINTER_V2_PROGRAM_ADDRESS,
>(
  input: HandleReceiveUnfinalizedMessageAsyncInput<
    TAccountAuthorityPda,
    TAccountTokenMessenger,
    TAccountRemoteTokenMessenger,
    TAccountTokenMinter,
    TAccountLocalToken,
    TAccountTokenPair,
    TAccountFeeRecipientTokenAccount,
    TAccountRecipientTokenAccount,
    TAccountCustodyTokenAccount,
    TAccountTokenProgram,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): Promise<
  HandleReceiveUnfinalizedMessageInstruction<
    TProgramAddress,
    TAccountAuthorityPda,
    TAccountTokenMessenger,
    TAccountRemoteTokenMessenger,
    TAccountTokenMinter,
    TAccountLocalToken,
    TAccountTokenPair,
    TAccountFeeRecipientTokenAccount,
    TAccountRecipientTokenAccount,
    TAccountCustodyTokenAccount,
    TAccountTokenProgram,
    TAccountEventAuthority,
    TAccountProgram
  >
> {
  // Program address.
  const programAddress =
    config?.programAddress ?? TOKEN_MESSENGER_MINTER_V2_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    authorityPda: { value: input.authorityPda ?? null, isWritable: false },
    tokenMessenger: { value: input.tokenMessenger ?? null, isWritable: false },
    remoteTokenMessenger: {
      value: input.remoteTokenMessenger ?? null,
      isWritable: false,
    },
    tokenMinter: { value: input.tokenMinter ?? null, isWritable: false },
    localToken: { value: input.localToken ?? null, isWritable: true },
    tokenPair: { value: input.tokenPair ?? null, isWritable: false },
    feeRecipientTokenAccount: {
      value: input.feeRecipientTokenAccount ?? null,
      isWritable: true,
    },
    recipientTokenAccount: {
      value: input.recipientTokenAccount ?? null,
      isWritable: true,
    },
    custodyTokenAccount: {
      value: input.custodyTokenAccount ?? null,
      isWritable: true,
    },
    tokenProgram: { value: input.tokenProgram ?? 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 getProgramDerivedAddress({
      programAddress:
        "CCTPV2Sm4AdWt5296sk4P66VBZ7bEhcARwFaaS9YPbeC" as Address<"CCTPV2Sm4AdWt5296sk4P66VBZ7bEhcARwFaaS9YPbeC">,
      seeds: [
        getBytesEncoder().encode(
          new Uint8Array([
            109, 101, 115, 115, 97, 103, 101, 95, 116, 114, 97, 110, 115, 109,
            105, 116, 116, 101, 114, 95, 97, 117, 116, 104, 111, 114, 105, 116,
            121,
          ]),
        ),
        getBytesEncoder().encode(
          new Uint8Array([
            166, 95, 200, 29, 15, 239, 168, 134, 12, 179, 184, 63, 8, 155, 2,
            36, 190, 138, 102, 135, 183, 174, 73, 245, 148, 192, 185, 180, 215,
            233, 56, 147,
          ]),
        ),
      ],
    });
  }
  if (!accounts.tokenProgram.value) {
    accounts.tokenProgram.value =
      "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" as Address<"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA">;
  }
  if (!accounts.eventAuthority.value) {
    accounts.eventAuthority.value = await findEventAuthorityPda();
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta(accounts.authorityPda),
      getAccountMeta(accounts.tokenMessenger),
      getAccountMeta(accounts.remoteTokenMessenger),
      getAccountMeta(accounts.tokenMinter),
      getAccountMeta(accounts.localToken),
      getAccountMeta(accounts.tokenPair),
      getAccountMeta(accounts.feeRecipientTokenAccount),
      getAccountMeta(accounts.recipientTokenAccount),
      getAccountMeta(accounts.custodyTokenAccount),
      getAccountMeta(accounts.tokenProgram),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getHandleReceiveUnfinalizedMessageInstructionDataEncoder().encode(
      args as HandleReceiveUnfinalizedMessageInstructionDataArgs,
    ),
    programAddress,
  } as HandleReceiveUnfinalizedMessageInstruction<
    TProgramAddress,
    TAccountAuthorityPda,
    TAccountTokenMessenger,
    TAccountRemoteTokenMessenger,
    TAccountTokenMinter,
    TAccountLocalToken,
    TAccountTokenPair,
    TAccountFeeRecipientTokenAccount,
    TAccountRecipientTokenAccount,
    TAccountCustodyTokenAccount,
    TAccountTokenProgram,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type HandleReceiveUnfinalizedMessageInput<
  TAccountAuthorityPda extends string = string,
  TAccountTokenMessenger extends string = string,
  TAccountRemoteTokenMessenger extends string = string,
  TAccountTokenMinter extends string = string,
  TAccountLocalToken extends string = string,
  TAccountTokenPair extends string = string,
  TAccountFeeRecipientTokenAccount extends string = string,
  TAccountRecipientTokenAccount extends string = string,
  TAccountCustodyTokenAccount extends string = string,
  TAccountTokenProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  authorityPda: TransactionSigner<TAccountAuthorityPda>;
  tokenMessenger: Address<TAccountTokenMessenger>;
  remoteTokenMessenger: Address<TAccountRemoteTokenMessenger>;
  tokenMinter: Address<TAccountTokenMinter>;
  localToken: Address<TAccountLocalToken>;
  tokenPair: Address<TAccountTokenPair>;
  feeRecipientTokenAccount: Address<TAccountFeeRecipientTokenAccount>;
  recipientTokenAccount: Address<TAccountRecipientTokenAccount>;
  custodyTokenAccount: Address<TAccountCustodyTokenAccount>;
  tokenProgram?: Address<TAccountTokenProgram>;
  eventAuthority: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  params: HandleReceiveUnfinalizedMessageInstructionDataArgs["params"];
};

export function getHandleReceiveUnfinalizedMessageInstruction<
  TAccountAuthorityPda extends string,
  TAccountTokenMessenger extends string,
  TAccountRemoteTokenMessenger extends string,
  TAccountTokenMinter extends string,
  TAccountLocalToken extends string,
  TAccountTokenPair extends string,
  TAccountFeeRecipientTokenAccount extends string,
  TAccountRecipientTokenAccount extends string,
  TAccountCustodyTokenAccount extends string,
  TAccountTokenProgram extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address =
    typeof TOKEN_MESSENGER_MINTER_V2_PROGRAM_ADDRESS,
>(
  input: HandleReceiveUnfinalizedMessageInput<
    TAccountAuthorityPda,
    TAccountTokenMessenger,
    TAccountRemoteTokenMessenger,
    TAccountTokenMinter,
    TAccountLocalToken,
    TAccountTokenPair,
    TAccountFeeRecipientTokenAccount,
    TAccountRecipientTokenAccount,
    TAccountCustodyTokenAccount,
    TAccountTokenProgram,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): HandleReceiveUnfinalizedMessageInstruction<
  TProgramAddress,
  TAccountAuthorityPda,
  TAccountTokenMessenger,
  TAccountRemoteTokenMessenger,
  TAccountTokenMinter,
  TAccountLocalToken,
  TAccountTokenPair,
  TAccountFeeRecipientTokenAccount,
  TAccountRecipientTokenAccount,
  TAccountCustodyTokenAccount,
  TAccountTokenProgram,
  TAccountEventAuthority,
  TAccountProgram
> {
  // Program address.
  const programAddress =
    config?.programAddress ?? TOKEN_MESSENGER_MINTER_V2_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    authorityPda: { value: input.authorityPda ?? null, isWritable: false },
    tokenMessenger: { value: input.tokenMessenger ?? null, isWritable: false },
    remoteTokenMessenger: {
      value: input.remoteTokenMessenger ?? null,
      isWritable: false,
    },
    tokenMinter: { value: input.tokenMinter ?? null, isWritable: false },
    localToken: { value: input.localToken ?? null, isWritable: true },
    tokenPair: { value: input.tokenPair ?? null, isWritable: false },
    feeRecipientTokenAccount: {
      value: input.feeRecipientTokenAccount ?? null,
      isWritable: true,
    },
    recipientTokenAccount: {
      value: input.recipientTokenAccount ?? null,
      isWritable: true,
    },
    custodyTokenAccount: {
      value: input.custodyTokenAccount ?? null,
      isWritable: true,
    },
    tokenProgram: { value: input.tokenProgram ?? 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.tokenProgram.value) {
    accounts.tokenProgram.value =
      "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" as Address<"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA">;
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta(accounts.authorityPda),
      getAccountMeta(accounts.tokenMessenger),
      getAccountMeta(accounts.remoteTokenMessenger),
      getAccountMeta(accounts.tokenMinter),
      getAccountMeta(accounts.localToken),
      getAccountMeta(accounts.tokenPair),
      getAccountMeta(accounts.feeRecipientTokenAccount),
      getAccountMeta(accounts.recipientTokenAccount),
      getAccountMeta(accounts.custodyTokenAccount),
      getAccountMeta(accounts.tokenProgram),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getHandleReceiveUnfinalizedMessageInstructionDataEncoder().encode(
      args as HandleReceiveUnfinalizedMessageInstructionDataArgs,
    ),
    programAddress,
  } as HandleReceiveUnfinalizedMessageInstruction<
    TProgramAddress,
    TAccountAuthorityPda,
    TAccountTokenMessenger,
    TAccountRemoteTokenMessenger,
    TAccountTokenMinter,
    TAccountLocalToken,
    TAccountTokenPair,
    TAccountFeeRecipientTokenAccount,
    TAccountRecipientTokenAccount,
    TAccountCustodyTokenAccount,
    TAccountTokenProgram,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type ParsedHandleReceiveUnfinalizedMessageInstruction<
  TProgram extends string = typeof TOKEN_MESSENGER_MINTER_V2_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    authorityPda: TAccountMetas[0];
    tokenMessenger: TAccountMetas[1];
    remoteTokenMessenger: TAccountMetas[2];
    tokenMinter: TAccountMetas[3];
    localToken: TAccountMetas[4];
    tokenPair: TAccountMetas[5];
    feeRecipientTokenAccount: TAccountMetas[6];
    recipientTokenAccount: TAccountMetas[7];
    custodyTokenAccount: TAccountMetas[8];
    tokenProgram: TAccountMetas[9];
    eventAuthority: TAccountMetas[10];
    program: TAccountMetas[11];
  };
  data: HandleReceiveUnfinalizedMessageInstructionData;
};

export function parseHandleReceiveUnfinalizedMessageInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>,
): ParsedHandleReceiveUnfinalizedMessageInstruction<TProgram, TAccountMetas> {
  if (instruction.accounts.length < 12) {
    // 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: {
      authorityPda: getNextAccount(),
      tokenMessenger: getNextAccount(),
      remoteTokenMessenger: getNextAccount(),
      tokenMinter: getNextAccount(),
      localToken: getNextAccount(),
      tokenPair: getNextAccount(),
      feeRecipientTokenAccount: getNextAccount(),
      recipientTokenAccount: getNextAccount(),
      custodyTokenAccount: getNextAccount(),
      tokenProgram: getNextAccount(),
      eventAuthority: getNextAccount(),
      program: getNextAccount(),
    },
    data: getHandleReceiveUnfinalizedMessageInstructionDataDecoder().decode(
      instruction.data,
    ),
  };
}
