/**
 * 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,
  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 ProgramDerivedAddress,
  type ReadonlyAccount,
  type ReadonlySignerAccount,
  type ReadonlyUint8Array,
  type TransactionSigner,
  type WritableAccount,
  type WritableSignerAccount,
} from "@solana/kit";
import {
  getAccountMetaFactory,
  getAddressFromResolvedInstructionAccount,
  getResolvedInstructionAccountAsProgramDerivedAddress,
  type ResolvedInstructionAccount,
} from "@solana/kit/program-client-core";
import { findEventAuthorityPda, findInstancePda } from "../pdas";
import { PRIVATE_CHANNEL_ESCROW_PROGRAM_PROGRAM_ADDRESS } from "../programs";

export const CREATE_INSTANCE_DISCRIMINATOR = 0;

export function getCreateInstanceDiscriminatorBytes(): ReadonlyUint8Array {
  return getU8Encoder().encode(CREATE_INSTANCE_DISCRIMINATOR);
}

export type CreateInstanceInstruction<
  TProgram extends string =
    typeof PRIVATE_CHANNEL_ESCROW_PROGRAM_PROGRAM_ADDRESS,
  TAccountPayer extends string | AccountMeta<string> = string,
  TAccountAdmin extends string | AccountMeta<string> = string,
  TAccountInstanceSeed extends string | AccountMeta<string> = string,
  TAccountInstance extends string | AccountMeta<string> = string,
  TAccountSystemProgram extends string | AccountMeta<string> =
    "11111111111111111111111111111111",
  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,
      TAccountAdmin extends string
        ? ReadonlySignerAccount<TAccountAdmin> &
            AccountSignerMeta<TAccountAdmin>
        : TAccountAdmin,
      TAccountInstanceSeed extends string
        ? ReadonlySignerAccount<TAccountInstanceSeed> &
            AccountSignerMeta<TAccountInstanceSeed>
        : TAccountInstanceSeed,
      TAccountInstance extends string
        ? WritableAccount<TAccountInstance>
        : TAccountInstance,
      TAccountSystemProgram extends string
        ? ReadonlyAccount<TAccountSystemProgram>
        : TAccountSystemProgram,
      TAccountEventAuthority extends string
        ? ReadonlyAccount<TAccountEventAuthority>
        : TAccountEventAuthority,
      TAccountPrivateChannelEscrowProgram extends string
        ? ReadonlyAccount<TAccountPrivateChannelEscrowProgram>
        : TAccountPrivateChannelEscrowProgram,
      ...TRemainingAccounts,
    ]
  >;

export type CreateInstanceInstructionData = {
  discriminator: number;
  bump: number;
};

export type CreateInstanceInstructionDataArgs = { bump: number };

export function getCreateInstanceInstructionDataEncoder(): FixedSizeEncoder<CreateInstanceInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", getU8Encoder()],
      ["bump", getU8Encoder()],
    ]),
    (value) => ({ ...value, discriminator: CREATE_INSTANCE_DISCRIMINATOR }),
  );
}

export function getCreateInstanceInstructionDataDecoder(): FixedSizeDecoder<CreateInstanceInstructionData> {
  return getStructDecoder([
    ["discriminator", getU8Decoder()],
    ["bump", getU8Decoder()],
  ]);
}

export function getCreateInstanceInstructionDataCodec(): FixedSizeCodec<
  CreateInstanceInstructionDataArgs,
  CreateInstanceInstructionData
> {
  return combineCodec(
    getCreateInstanceInstructionDataEncoder(),
    getCreateInstanceInstructionDataDecoder(),
  );
}

export type CreateInstanceAsyncInput<
  TAccountPayer extends string = string,
  TAccountAdmin extends string = string,
  TAccountInstanceSeed extends string = string,
  TAccountInstance extends string = string,
  TAccountSystemProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountPrivateChannelEscrowProgram extends string = string,
> = {
  /** Transaction fee payer */
  payer: TransactionSigner<TAccountPayer>;
  /** Admin of Instance */
  admin: TransactionSigner<TAccountAdmin>;
  /** Instance seed signer for PDA derivation */
  instanceSeed: TransactionSigner<TAccountInstanceSeed>;
  /** Instance PDA to be created */
  instance?: ProgramDerivedAddress<TAccountInstance>;
  /** System program */
  systemProgram?: Address<TAccountSystemProgram>;
  /** Event authority PDA for emitting events */
  eventAuthority?: Address<TAccountEventAuthority>;
  /** Current program for CPI */
  privateChannelEscrowProgram?: Address<TAccountPrivateChannelEscrowProgram>;
  bump?: CreateInstanceInstructionDataArgs["bump"];
};

export async function getCreateInstanceInstructionAsync<
  TAccountPayer extends string,
  TAccountAdmin extends string,
  TAccountInstanceSeed extends string,
  TAccountInstance extends string,
  TAccountSystemProgram extends string,
  TAccountEventAuthority extends string,
  TAccountPrivateChannelEscrowProgram extends string,
  TProgramAddress extends Address =
    typeof PRIVATE_CHANNEL_ESCROW_PROGRAM_PROGRAM_ADDRESS,
>(
  input: CreateInstanceAsyncInput<
    TAccountPayer,
    TAccountAdmin,
    TAccountInstanceSeed,
    TAccountInstance,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountPrivateChannelEscrowProgram
  >,
  config?: { programAddress?: TProgramAddress },
): Promise<
  CreateInstanceInstruction<
    TProgramAddress,
    TAccountPayer,
    TAccountAdmin,
    TAccountInstanceSeed,
    TAccountInstance,
    TAccountSystemProgram,
    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 },
    admin: { value: input.admin ?? null, isWritable: false },
    instanceSeed: { value: input.instanceSeed ?? null, isWritable: false },
    instance: { value: input.instance ?? null, isWritable: true },
    systemProgram: { value: input.systemProgram ?? 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.instance.value) {
    accounts.instance.value = await findInstancePda({
      instanceSeed: getAddressFromResolvedInstructionAccount(
        "instanceSeed",
        accounts.instanceSeed.value,
      ),
    });
  }
  if (!accounts.systemProgram.value) {
    accounts.systemProgram.value =
      "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">;
  }
  if (!accounts.eventAuthority.value) {
    accounts.eventAuthority.value = await findEventAuthorityPda();
  }
  if (!accounts.privateChannelEscrowProgram.value) {
    accounts.privateChannelEscrowProgram.value =
      "9tgHa1DcnaSSUtmMsst8ovKTe1Gfxzezn27KnH9xXYeU" as Address<"9tgHa1DcnaSSUtmMsst8ovKTe1Gfxzezn27KnH9xXYeU">;
  }
  if (!args.bump) {
    args.bump = getResolvedInstructionAccountAsProgramDerivedAddress(
      "instance",
      accounts.instance.value,
    )[1];
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta("payer", accounts.payer),
      getAccountMeta("admin", accounts.admin),
      getAccountMeta("instanceSeed", accounts.instanceSeed),
      getAccountMeta("instance", accounts.instance),
      getAccountMeta("systemProgram", accounts.systemProgram),
      getAccountMeta("eventAuthority", accounts.eventAuthority),
      getAccountMeta(
        "privateChannelEscrowProgram",
        accounts.privateChannelEscrowProgram,
      ),
    ],
    data: getCreateInstanceInstructionDataEncoder().encode(
      args as CreateInstanceInstructionDataArgs,
    ),
    programAddress,
  } as CreateInstanceInstruction<
    TProgramAddress,
    TAccountPayer,
    TAccountAdmin,
    TAccountInstanceSeed,
    TAccountInstance,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountPrivateChannelEscrowProgram
  >);
}

export type CreateInstanceInput<
  TAccountPayer extends string = string,
  TAccountAdmin extends string = string,
  TAccountInstanceSeed extends string = string,
  TAccountInstance extends string = string,
  TAccountSystemProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountPrivateChannelEscrowProgram extends string = string,
> = {
  /** Transaction fee payer */
  payer: TransactionSigner<TAccountPayer>;
  /** Admin of Instance */
  admin: TransactionSigner<TAccountAdmin>;
  /** Instance seed signer for PDA derivation */
  instanceSeed: TransactionSigner<TAccountInstanceSeed>;
  /** Instance PDA to be created */
  instance: ProgramDerivedAddress<TAccountInstance>;
  /** System program */
  systemProgram?: Address<TAccountSystemProgram>;
  /** Event authority PDA for emitting events */
  eventAuthority: Address<TAccountEventAuthority>;
  /** Current program for CPI */
  privateChannelEscrowProgram?: Address<TAccountPrivateChannelEscrowProgram>;
  bump?: CreateInstanceInstructionDataArgs["bump"];
};

export function getCreateInstanceInstruction<
  TAccountPayer extends string,
  TAccountAdmin extends string,
  TAccountInstanceSeed extends string,
  TAccountInstance extends string,
  TAccountSystemProgram extends string,
  TAccountEventAuthority extends string,
  TAccountPrivateChannelEscrowProgram extends string,
  TProgramAddress extends Address =
    typeof PRIVATE_CHANNEL_ESCROW_PROGRAM_PROGRAM_ADDRESS,
>(
  input: CreateInstanceInput<
    TAccountPayer,
    TAccountAdmin,
    TAccountInstanceSeed,
    TAccountInstance,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountPrivateChannelEscrowProgram
  >,
  config?: { programAddress?: TProgramAddress },
): CreateInstanceInstruction<
  TProgramAddress,
  TAccountPayer,
  TAccountAdmin,
  TAccountInstanceSeed,
  TAccountInstance,
  TAccountSystemProgram,
  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 },
    admin: { value: input.admin ?? null, isWritable: false },
    instanceSeed: { value: input.instanceSeed ?? null, isWritable: false },
    instance: { value: input.instance ?? null, isWritable: true },
    systemProgram: { value: input.systemProgram ?? 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.systemProgram.value) {
    accounts.systemProgram.value =
      "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">;
  }
  if (!accounts.privateChannelEscrowProgram.value) {
    accounts.privateChannelEscrowProgram.value =
      "9tgHa1DcnaSSUtmMsst8ovKTe1Gfxzezn27KnH9xXYeU" as Address<"9tgHa1DcnaSSUtmMsst8ovKTe1Gfxzezn27KnH9xXYeU">;
  }
  if (!args.bump) {
    args.bump = getResolvedInstructionAccountAsProgramDerivedAddress(
      "instance",
      accounts.instance.value,
    )[1];
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta("payer", accounts.payer),
      getAccountMeta("admin", accounts.admin),
      getAccountMeta("instanceSeed", accounts.instanceSeed),
      getAccountMeta("instance", accounts.instance),
      getAccountMeta("systemProgram", accounts.systemProgram),
      getAccountMeta("eventAuthority", accounts.eventAuthority),
      getAccountMeta(
        "privateChannelEscrowProgram",
        accounts.privateChannelEscrowProgram,
      ),
    ],
    data: getCreateInstanceInstructionDataEncoder().encode(
      args as CreateInstanceInstructionDataArgs,
    ),
    programAddress,
  } as CreateInstanceInstruction<
    TProgramAddress,
    TAccountPayer,
    TAccountAdmin,
    TAccountInstanceSeed,
    TAccountInstance,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountPrivateChannelEscrowProgram
  >);
}

export type ParsedCreateInstanceInstruction<
  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];
    /** Admin of Instance */
    admin: TAccountMetas[1];
    /** Instance seed signer for PDA derivation */
    instanceSeed: TAccountMetas[2];
    /** Instance PDA to be created */
    instance: TAccountMetas[3];
    /** System program */
    systemProgram: TAccountMetas[4];
    /** Event authority PDA for emitting events */
    eventAuthority: TAccountMetas[5];
    /** Current program for CPI */
    privateChannelEscrowProgram: TAccountMetas[6];
  };
  data: CreateInstanceInstructionData;
};

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