/**
 * 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,
  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,
} from "@solana/kit";
import { findEventAuthorityPda } from "../pdas";
import { TOKEN_MESSENGER_MINTER_V2_PROGRAM_ADDRESS } from "../programs";
import { getAccountMetaFactory, type ResolvedAccount } from "../shared";

export const SET_TOKEN_CONTROLLER_DISCRIMINATOR = new Uint8Array([
  88, 6, 98, 10, 79, 59, 15, 24,
]);

export function getSetTokenControllerDiscriminatorBytes() {
  return fixEncoderSize(getBytesEncoder(), 8).encode(
    SET_TOKEN_CONTROLLER_DISCRIMINATOR,
  );
}

export type SetTokenControllerInstruction<
  TProgram extends string = typeof TOKEN_MESSENGER_MINTER_V2_PROGRAM_ADDRESS,
  TAccountOwner extends string | AccountMeta<string> = string,
  TAccountTokenMessenger extends string | AccountMeta<string> = string,
  TAccountTokenMinter extends string | AccountMeta<string> = string,
  TAccountEventAuthority extends string | AccountMeta<string> = string,
  TAccountProgram extends string | AccountMeta<string> = string,
  TRemainingAccounts extends readonly AccountMeta<string>[] = [],
> = Instruction<TProgram> &
  InstructionWithData<ReadonlyUint8Array> &
  InstructionWithAccounts<
    [
      TAccountOwner extends string
        ? ReadonlySignerAccount<TAccountOwner> &
            AccountSignerMeta<TAccountOwner>
        : TAccountOwner,
      TAccountTokenMessenger extends string
        ? ReadonlyAccount<TAccountTokenMessenger>
        : TAccountTokenMessenger,
      TAccountTokenMinter extends string
        ? WritableAccount<TAccountTokenMinter>
        : TAccountTokenMinter,
      TAccountEventAuthority extends string
        ? ReadonlyAccount<TAccountEventAuthority>
        : TAccountEventAuthority,
      TAccountProgram extends string
        ? ReadonlyAccount<TAccountProgram>
        : TAccountProgram,
      ...TRemainingAccounts,
    ]
  >;

export type SetTokenControllerInstructionData = {
  discriminator: ReadonlyUint8Array;
  tokenController: Address;
};

export type SetTokenControllerInstructionDataArgs = {
  tokenController: Address;
};

export function getSetTokenControllerInstructionDataEncoder(): FixedSizeEncoder<SetTokenControllerInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", fixEncoderSize(getBytesEncoder(), 8)],
      ["tokenController", getAddressEncoder()],
    ]),
    (value) => ({
      ...value,
      discriminator: SET_TOKEN_CONTROLLER_DISCRIMINATOR,
    }),
  );
}

export function getSetTokenControllerInstructionDataDecoder(): FixedSizeDecoder<SetTokenControllerInstructionData> {
  return getStructDecoder([
    ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
    ["tokenController", getAddressDecoder()],
  ]);
}

export function getSetTokenControllerInstructionDataCodec(): FixedSizeCodec<
  SetTokenControllerInstructionDataArgs,
  SetTokenControllerInstructionData
> {
  return combineCodec(
    getSetTokenControllerInstructionDataEncoder(),
    getSetTokenControllerInstructionDataDecoder(),
  );
}

export type SetTokenControllerAsyncInput<
  TAccountOwner extends string = string,
  TAccountTokenMessenger extends string = string,
  TAccountTokenMinter extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  owner: TransactionSigner<TAccountOwner>;
  tokenMessenger: Address<TAccountTokenMessenger>;
  tokenMinter: Address<TAccountTokenMinter>;
  eventAuthority?: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  tokenController: SetTokenControllerInstructionDataArgs["tokenController"];
};

export async function getSetTokenControllerInstructionAsync<
  TAccountOwner extends string,
  TAccountTokenMessenger extends string,
  TAccountTokenMinter extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address =
    typeof TOKEN_MESSENGER_MINTER_V2_PROGRAM_ADDRESS,
>(
  input: SetTokenControllerAsyncInput<
    TAccountOwner,
    TAccountTokenMessenger,
    TAccountTokenMinter,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): Promise<
  SetTokenControllerInstruction<
    TProgramAddress,
    TAccountOwner,
    TAccountTokenMessenger,
    TAccountTokenMinter,
    TAccountEventAuthority,
    TAccountProgram
  >
> {
  // Program address.
  const programAddress =
    config?.programAddress ?? TOKEN_MESSENGER_MINTER_V2_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    owner: { value: input.owner ?? null, isWritable: false },
    tokenMessenger: { value: input.tokenMessenger ?? null, isWritable: false },
    tokenMinter: { value: input.tokenMinter ?? null, isWritable: true },
    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.eventAuthority.value) {
    accounts.eventAuthority.value = await findEventAuthorityPda();
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta(accounts.owner),
      getAccountMeta(accounts.tokenMessenger),
      getAccountMeta(accounts.tokenMinter),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getSetTokenControllerInstructionDataEncoder().encode(
      args as SetTokenControllerInstructionDataArgs,
    ),
    programAddress,
  } as SetTokenControllerInstruction<
    TProgramAddress,
    TAccountOwner,
    TAccountTokenMessenger,
    TAccountTokenMinter,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type SetTokenControllerInput<
  TAccountOwner extends string = string,
  TAccountTokenMessenger extends string = string,
  TAccountTokenMinter extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  owner: TransactionSigner<TAccountOwner>;
  tokenMessenger: Address<TAccountTokenMessenger>;
  tokenMinter: Address<TAccountTokenMinter>;
  eventAuthority: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  tokenController: SetTokenControllerInstructionDataArgs["tokenController"];
};

export function getSetTokenControllerInstruction<
  TAccountOwner extends string,
  TAccountTokenMessenger extends string,
  TAccountTokenMinter extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address =
    typeof TOKEN_MESSENGER_MINTER_V2_PROGRAM_ADDRESS,
>(
  input: SetTokenControllerInput<
    TAccountOwner,
    TAccountTokenMessenger,
    TAccountTokenMinter,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): SetTokenControllerInstruction<
  TProgramAddress,
  TAccountOwner,
  TAccountTokenMessenger,
  TAccountTokenMinter,
  TAccountEventAuthority,
  TAccountProgram
> {
  // Program address.
  const programAddress =
    config?.programAddress ?? TOKEN_MESSENGER_MINTER_V2_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    owner: { value: input.owner ?? null, isWritable: false },
    tokenMessenger: { value: input.tokenMessenger ?? null, isWritable: false },
    tokenMinter: { value: input.tokenMinter ?? null, isWritable: true },
    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 };

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta(accounts.owner),
      getAccountMeta(accounts.tokenMessenger),
      getAccountMeta(accounts.tokenMinter),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getSetTokenControllerInstructionDataEncoder().encode(
      args as SetTokenControllerInstructionDataArgs,
    ),
    programAddress,
  } as SetTokenControllerInstruction<
    TProgramAddress,
    TAccountOwner,
    TAccountTokenMessenger,
    TAccountTokenMinter,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type ParsedSetTokenControllerInstruction<
  TProgram extends string = typeof TOKEN_MESSENGER_MINTER_V2_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    owner: TAccountMetas[0];
    tokenMessenger: TAccountMetas[1];
    tokenMinter: TAccountMetas[2];
    eventAuthority: TAccountMetas[3];
    program: TAccountMetas[4];
  };
  data: SetTokenControllerInstructionData;
};

export function parseSetTokenControllerInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>,
): ParsedSetTokenControllerInstruction<TProgram, TAccountMetas> {
  if (instruction.accounts.length < 5) {
    // 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: {
      owner: getNextAccount(),
      tokenMessenger: getNextAccount(),
      tokenMinter: getNextAccount(),
      eventAuthority: getNextAccount(),
      program: getNextAccount(),
    },
    data: getSetTokenControllerInstructionDataDecoder().decode(
      instruction.data,
    ),
  };
}
