/**
 * 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,
  getStructDecoder,
  getStructEncoder,
  getU64Decoder,
  getU64Encoder,
  getU8Decoder,
  getU8Encoder,
  SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS,
  SolanaError,
  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 {
  getAccountMetaFactory,
  getAddressFromResolvedInstructionAccount,
  type ResolvedInstructionAccount,
} from "@solana/kit/program-client-core";
import { findEventAuthorityPda, findOperatorPda } from "../pdas";
import { PRIVATE_CHANNEL_ESCROW_PROGRAM_PROGRAM_ADDRESS } from "../programs";

export const RESET_SMT_ROOT_DISCRIMINATOR = 8;

export function getResetSmtRootDiscriminatorBytes(): ReadonlyUint8Array {
  return getU8Encoder().encode(RESET_SMT_ROOT_DISCRIMINATOR);
}

export type ResetSmtRootInstruction<
  TProgram extends string =
    typeof PRIVATE_CHANNEL_ESCROW_PROGRAM_PROGRAM_ADDRESS,
  TAccountPayer extends string | AccountMeta<string> = string,
  TAccountOperator extends string | AccountMeta<string> = string,
  TAccountInstance extends string | AccountMeta<string> = string,
  TAccountOperatorPda extends string | AccountMeta<string> = string,
  TAccountEventAuthority extends string | AccountMeta<string> = string,
  TAccountPrivateChannelEscrowProgram extends string | AccountMeta<string> =
    "9tgHa1DcnaSSUtmMsst8ovKTe1Gfxzezn27KnH9xXYeU",
  TRemainingAccounts extends readonly AccountMeta<string>[] = [],
> = Instruction<TProgram> &
  InstructionWithData<ReadonlyUint8Array> &
  InstructionWithAccounts<
    [
      TAccountPayer extends string
        ? WritableSignerAccount<TAccountPayer> &
            AccountSignerMeta<TAccountPayer>
        : TAccountPayer,
      TAccountOperator extends string
        ? ReadonlySignerAccount<TAccountOperator> &
            AccountSignerMeta<TAccountOperator>
        : TAccountOperator,
      TAccountInstance extends string
        ? WritableAccount<TAccountInstance>
        : TAccountInstance,
      TAccountOperatorPda extends string
        ? ReadonlyAccount<TAccountOperatorPda>
        : TAccountOperatorPda,
      TAccountEventAuthority extends string
        ? ReadonlyAccount<TAccountEventAuthority>
        : TAccountEventAuthority,
      TAccountPrivateChannelEscrowProgram extends string
        ? ReadonlyAccount<TAccountPrivateChannelEscrowProgram>
        : TAccountPrivateChannelEscrowProgram,
      ...TRemainingAccounts,
    ]
  >;

export type ResetSmtRootInstructionData = {
  discriminator: number;
  expectedCurrentTreeIndex: bigint;
};

export type ResetSmtRootInstructionDataArgs = {
  expectedCurrentTreeIndex: number | bigint;
};

export function getResetSmtRootInstructionDataEncoder(): FixedSizeEncoder<ResetSmtRootInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", getU8Encoder()],
      ["expectedCurrentTreeIndex", getU64Encoder()],
    ]),
    (value) => ({ ...value, discriminator: RESET_SMT_ROOT_DISCRIMINATOR }),
  );
}

export function getResetSmtRootInstructionDataDecoder(): FixedSizeDecoder<ResetSmtRootInstructionData> {
  return getStructDecoder([
    ["discriminator", getU8Decoder()],
    ["expectedCurrentTreeIndex", getU64Decoder()],
  ]);
}

export function getResetSmtRootInstructionDataCodec(): FixedSizeCodec<
  ResetSmtRootInstructionDataArgs,
  ResetSmtRootInstructionData
> {
  return combineCodec(
    getResetSmtRootInstructionDataEncoder(),
    getResetSmtRootInstructionDataDecoder(),
  );
}

export type ResetSmtRootAsyncInput<
  TAccountPayer extends string = string,
  TAccountOperator extends string = string,
  TAccountInstance extends string = string,
  TAccountOperatorPda extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountPrivateChannelEscrowProgram extends string = string,
> = {
  /** Transaction fee payer */
  payer: TransactionSigner<TAccountPayer>;
  /** Operator resetting the SMT root */
  operator: TransactionSigner<TAccountOperator>;
  /** Instance PDA to reset */
  instance: Address<TAccountInstance>;
  /** Operator PDA to validate operator permissions */
  operatorPda?: Address<TAccountOperatorPda>;
  /** Event authority PDA for emitting events */
  eventAuthority?: Address<TAccountEventAuthority>;
  /** Current program for CPI */
  privateChannelEscrowProgram?: Address<TAccountPrivateChannelEscrowProgram>;
  expectedCurrentTreeIndex: ResetSmtRootInstructionDataArgs["expectedCurrentTreeIndex"];
};

export async function getResetSmtRootInstructionAsync<
  TAccountPayer extends string,
  TAccountOperator extends string,
  TAccountInstance extends string,
  TAccountOperatorPda extends string,
  TAccountEventAuthority extends string,
  TAccountPrivateChannelEscrowProgram extends string,
  TProgramAddress extends Address =
    typeof PRIVATE_CHANNEL_ESCROW_PROGRAM_PROGRAM_ADDRESS,
>(
  input: ResetSmtRootAsyncInput<
    TAccountPayer,
    TAccountOperator,
    TAccountInstance,
    TAccountOperatorPda,
    TAccountEventAuthority,
    TAccountPrivateChannelEscrowProgram
  >,
  config?: { programAddress?: TProgramAddress },
): Promise<
  ResetSmtRootInstruction<
    TProgramAddress,
    TAccountPayer,
    TAccountOperator,
    TAccountInstance,
    TAccountOperatorPda,
    TAccountEventAuthority,
    TAccountPrivateChannelEscrowProgram
  >
> {
  // Program address.
  const programAddress =
    config?.programAddress ?? PRIVATE_CHANNEL_ESCROW_PROGRAM_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    payer: { value: input.payer ?? null, isWritable: true },
    operator: { value: input.operator ?? null, isWritable: false },
    instance: { value: input.instance ?? null, isWritable: true },
    operatorPda: { value: input.operatorPda ?? null, isWritable: false },
    eventAuthority: { value: input.eventAuthority ?? null, isWritable: false },
    privateChannelEscrowProgram: {
      value: input.privateChannelEscrowProgram ?? null,
      isWritable: false,
    },
  };
  const accounts = originalAccounts as Record<
    keyof typeof originalAccounts,
    ResolvedInstructionAccount
  >;

  // Original args.
  const args = { ...input };

  // Resolve default values.
  if (!accounts.operatorPda.value) {
    accounts.operatorPda.value = await findOperatorPda({
      instance: getAddressFromResolvedInstructionAccount(
        "instance",
        accounts.instance.value,
      ),
      wallet: getAddressFromResolvedInstructionAccount(
        "operator",
        accounts.operator.value,
      ),
    });
  }
  if (!accounts.eventAuthority.value) {
    accounts.eventAuthority.value = await findEventAuthorityPda();
  }
  if (!accounts.privateChannelEscrowProgram.value) {
    accounts.privateChannelEscrowProgram.value =
      "9tgHa1DcnaSSUtmMsst8ovKTe1Gfxzezn27KnH9xXYeU" as Address<"9tgHa1DcnaSSUtmMsst8ovKTe1Gfxzezn27KnH9xXYeU">;
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta("payer", accounts.payer),
      getAccountMeta("operator", accounts.operator),
      getAccountMeta("instance", accounts.instance),
      getAccountMeta("operatorPda", accounts.operatorPda),
      getAccountMeta("eventAuthority", accounts.eventAuthority),
      getAccountMeta(
        "privateChannelEscrowProgram",
        accounts.privateChannelEscrowProgram,
      ),
    ],
    data: getResetSmtRootInstructionDataEncoder().encode(
      args as ResetSmtRootInstructionDataArgs,
    ),
    programAddress,
  } as ResetSmtRootInstruction<
    TProgramAddress,
    TAccountPayer,
    TAccountOperator,
    TAccountInstance,
    TAccountOperatorPda,
    TAccountEventAuthority,
    TAccountPrivateChannelEscrowProgram
  >);
}

export type ResetSmtRootInput<
  TAccountPayer extends string = string,
  TAccountOperator extends string = string,
  TAccountInstance extends string = string,
  TAccountOperatorPda extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountPrivateChannelEscrowProgram extends string = string,
> = {
  /** Transaction fee payer */
  payer: TransactionSigner<TAccountPayer>;
  /** Operator resetting the SMT root */
  operator: TransactionSigner<TAccountOperator>;
  /** Instance PDA to reset */
  instance: Address<TAccountInstance>;
  /** Operator PDA to validate operator permissions */
  operatorPda: Address<TAccountOperatorPda>;
  /** Event authority PDA for emitting events */
  eventAuthority: Address<TAccountEventAuthority>;
  /** Current program for CPI */
  privateChannelEscrowProgram?: Address<TAccountPrivateChannelEscrowProgram>;
  expectedCurrentTreeIndex: ResetSmtRootInstructionDataArgs["expectedCurrentTreeIndex"];
};

export function getResetSmtRootInstruction<
  TAccountPayer extends string,
  TAccountOperator extends string,
  TAccountInstance extends string,
  TAccountOperatorPda extends string,
  TAccountEventAuthority extends string,
  TAccountPrivateChannelEscrowProgram extends string,
  TProgramAddress extends Address =
    typeof PRIVATE_CHANNEL_ESCROW_PROGRAM_PROGRAM_ADDRESS,
>(
  input: ResetSmtRootInput<
    TAccountPayer,
    TAccountOperator,
    TAccountInstance,
    TAccountOperatorPda,
    TAccountEventAuthority,
    TAccountPrivateChannelEscrowProgram
  >,
  config?: { programAddress?: TProgramAddress },
): ResetSmtRootInstruction<
  TProgramAddress,
  TAccountPayer,
  TAccountOperator,
  TAccountInstance,
  TAccountOperatorPda,
  TAccountEventAuthority,
  TAccountPrivateChannelEscrowProgram
> {
  // Program address.
  const programAddress =
    config?.programAddress ?? PRIVATE_CHANNEL_ESCROW_PROGRAM_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    payer: { value: input.payer ?? null, isWritable: true },
    operator: { value: input.operator ?? null, isWritable: false },
    instance: { value: input.instance ?? null, isWritable: true },
    operatorPda: { value: input.operatorPda ?? null, isWritable: false },
    eventAuthority: { value: input.eventAuthority ?? null, isWritable: false },
    privateChannelEscrowProgram: {
      value: input.privateChannelEscrowProgram ?? null,
      isWritable: false,
    },
  };
  const accounts = originalAccounts as Record<
    keyof typeof originalAccounts,
    ResolvedInstructionAccount
  >;

  // Original args.
  const args = { ...input };

  // Resolve default values.
  if (!accounts.privateChannelEscrowProgram.value) {
    accounts.privateChannelEscrowProgram.value =
      "9tgHa1DcnaSSUtmMsst8ovKTe1Gfxzezn27KnH9xXYeU" as Address<"9tgHa1DcnaSSUtmMsst8ovKTe1Gfxzezn27KnH9xXYeU">;
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta("payer", accounts.payer),
      getAccountMeta("operator", accounts.operator),
      getAccountMeta("instance", accounts.instance),
      getAccountMeta("operatorPda", accounts.operatorPda),
      getAccountMeta("eventAuthority", accounts.eventAuthority),
      getAccountMeta(
        "privateChannelEscrowProgram",
        accounts.privateChannelEscrowProgram,
      ),
    ],
    data: getResetSmtRootInstructionDataEncoder().encode(
      args as ResetSmtRootInstructionDataArgs,
    ),
    programAddress,
  } as ResetSmtRootInstruction<
    TProgramAddress,
    TAccountPayer,
    TAccountOperator,
    TAccountInstance,
    TAccountOperatorPda,
    TAccountEventAuthority,
    TAccountPrivateChannelEscrowProgram
  >);
}

export type ParsedResetSmtRootInstruction<
  TProgram extends string =
    typeof PRIVATE_CHANNEL_ESCROW_PROGRAM_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    /** Transaction fee payer */
    payer: TAccountMetas[0];
    /** Operator resetting the SMT root */
    operator: TAccountMetas[1];
    /** Instance PDA to reset */
    instance: TAccountMetas[2];
    /** Operator PDA to validate operator permissions */
    operatorPda: TAccountMetas[3];
    /** Event authority PDA for emitting events */
    eventAuthority: TAccountMetas[4];
    /** Current program for CPI */
    privateChannelEscrowProgram: TAccountMetas[5];
  };
  data: ResetSmtRootInstructionData;
};

export function parseResetSmtRootInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>,
): ParsedResetSmtRootInstruction<TProgram, TAccountMetas> {
  if (instruction.accounts.length < 6) {
    throw new SolanaError(
      SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS,
      {
        actualAccountMetas: instruction.accounts.length,
        expectedAccountMetas: 6,
      },
    );
  }
  let accountIndex = 0;
  const getNextAccount = () => {
    const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;
    accountIndex += 1;
    return accountMeta;
  };
  return {
    programAddress: instruction.programAddress,
    accounts: {
      payer: getNextAccount(),
      operator: getNextAccount(),
      instance: getNextAccount(),
      operatorPda: getNextAccount(),
      eventAuthority: getNextAccount(),
      privateChannelEscrowProgram: getNextAccount(),
    },
    data: getResetSmtRootInstructionDataDecoder().decode(instruction.data),
  };
}
