/**
 * 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 {
  AccountRole,
  combineCodec,
  getStructDecoder,
  getStructEncoder,
  getU8Decoder,
  getU8Encoder,
  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 { TOKEN_PROGRAM_ADDRESS } from '../programs';
import { getAccountMetaFactory, type ResolvedAccount } from '../shared';

export const REVOKE_DISCRIMINATOR = 5;

export function getRevokeDiscriminatorBytes() {
  return getU8Encoder().encode(REVOKE_DISCRIMINATOR);
}

export type RevokeInstruction<
  TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,
  TAccountSource extends string | AccountMeta<string> = string,
  TAccountOwner extends string | AccountMeta<string> = string,
  TRemainingAccounts extends readonly AccountMeta<string>[] = [],
> = Instruction<TProgram> &
  InstructionWithData<ReadonlyUint8Array> &
  InstructionWithAccounts<
    [
      TAccountSource extends string
        ? WritableAccount<TAccountSource>
        : TAccountSource,
      TAccountOwner extends string
        ? ReadonlyAccount<TAccountOwner>
        : TAccountOwner,
      ...TRemainingAccounts,
    ]
  >;

export type RevokeInstructionData = { discriminator: number };

export type RevokeInstructionDataArgs = {};

export function getRevokeInstructionDataEncoder(): FixedSizeEncoder<RevokeInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([['discriminator', getU8Encoder()]]),
    (value) => ({ ...value, discriminator: REVOKE_DISCRIMINATOR })
  ) as FixedSizeEncoder<RevokeInstructionDataArgs>;
}

export function getRevokeInstructionDataDecoder(): FixedSizeDecoder<RevokeInstructionData> {
  return getStructDecoder([
    ['discriminator', getU8Decoder()],
  ]) as FixedSizeDecoder<RevokeInstructionData>;
}

export function getRevokeInstructionDataCodec(): FixedSizeCodec<
  RevokeInstructionDataArgs,
  RevokeInstructionData
> {
  return combineCodec(
    getRevokeInstructionDataEncoder(),
    getRevokeInstructionDataDecoder()
  ) as FixedSizeCodec<RevokeInstructionDataArgs, RevokeInstructionData>;
}

export type RevokeInput<
  TAccountSource extends string = string,
  TAccountOwner extends string = string,
> = {
  /** The source account. */
  source: Address<TAccountSource>;
  /** The source account owner or its multisignature. */
  owner: Address<TAccountOwner> | TransactionSigner<TAccountOwner>;
  multiSigners?: Array<TransactionSigner>;
};

export function getRevokeInstruction<
  TAccountSource extends string,
  TAccountOwner extends string,
  TProgramAddress extends Address = typeof TOKEN_PROGRAM_ADDRESS,
>(
  input: RevokeInput<TAccountSource, TAccountOwner>,
  config?: { programAddress?: TProgramAddress }
): RevokeInstruction<
  TProgramAddress,
  TAccountSource,
  (typeof input)['owner'] extends TransactionSigner<TAccountOwner>
    ? ReadonlySignerAccount<TAccountOwner> & AccountSignerMeta<TAccountOwner>
    : TAccountOwner
> {
  // Program address.
  const programAddress = config?.programAddress ?? TOKEN_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    source: { value: input.source ?? null, isWritable: true },
    owner: { value: input.owner ?? null, isWritable: false },
  };
  const accounts = originalAccounts as Record<
    keyof typeof originalAccounts,
    ResolvedAccount
  >;

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

  // Remaining accounts.
  const remainingAccounts: AccountMeta[] = (args.multiSigners ?? []).map(
    (signer) => ({
      address: signer.address,
      role: AccountRole.READONLY_SIGNER,
      signer,
    })
  );

  const getAccountMeta = getAccountMetaFactory(programAddress, 'programId');
  const instruction = {
    accounts: [
      getAccountMeta(accounts.source),
      getAccountMeta(accounts.owner),
      ...remainingAccounts,
    ],
    programAddress,
    data: getRevokeInstructionDataEncoder().encode({}),
  } as RevokeInstruction<
    TProgramAddress,
    TAccountSource,
    (typeof input)['owner'] extends TransactionSigner<TAccountOwner>
      ? ReadonlySignerAccount<TAccountOwner> & AccountSignerMeta<TAccountOwner>
      : TAccountOwner
  >;

  return instruction;
}

export type ParsedRevokeInstruction<
  TProgram extends string = typeof TOKEN_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    /** The source account. */
    source: TAccountMetas[0];
    /** The source account owner or its multisignature. */
    owner: TAccountMetas[1];
  };
  data: RevokeInstructionData;
};

export function parseRevokeInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>
): ParsedRevokeInstruction<TProgram, TAccountMetas> {
  if (instruction.accounts.length < 2) {
    // TODO: Coded error.
    throw new Error('Not enough accounts');
  }
  let accountIndex = 0;
  const getNextAccount = () => {
    const accountMeta = instruction.accounts![accountIndex]!;
    accountIndex += 1;
    return accountMeta;
  };
  return {
    programAddress: instruction.programAddress,
    accounts: {
      source: getNextAccount(),
      owner: getNextAccount(),
    },
    data: getRevokeInstructionDataDecoder().decode(instruction.data),
  };
}
