/**
 * 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 {
  addDecoderSizePrefix,
  addEncoderSizePrefix,
  combineCodec,
  fixDecoderSize,
  fixEncoderSize,
  getAddressDecoder,
  getAddressEncoder,
  getBytesDecoder,
  getBytesEncoder,
  getProgramDerivedAddress,
  getStructDecoder,
  getStructEncoder,
  getU32Decoder,
  getU32Encoder,
  getU64Decoder,
  getU64Encoder,
  transformEncoder,
  type AccountMeta,
  type AccountSignerMeta,
  type Address,
  type Codec,
  type Decoder,
  type Encoder,
  type Instruction,
  type InstructionWithAccounts,
  type InstructionWithData,
  type ReadonlyAccount,
  type ReadonlyUint8Array,
  type TransactionSigner,
  type WritableAccount,
  type WritableSignerAccount,
} from "@solana/kit";
import { findEventAuthorityPda } from "../pdas";
import { SVM_SPOKE_PROGRAM_ADDRESS } from "../programs";
import {
  expectAddress,
  expectSome,
  getAccountMetaFactory,
  type ResolvedAccount,
} from "../shared";

export const DEPOSIT_DISCRIMINATOR = new Uint8Array([
  242, 35, 198, 137, 82, 225, 242, 182,
]);

export function getDepositDiscriminatorBytes() {
  return fixEncoderSize(getBytesEncoder(), 8).encode(DEPOSIT_DISCRIMINATOR);
}

export type DepositInstruction<
  TProgram extends string = typeof SVM_SPOKE_PROGRAM_ADDRESS,
  TAccountSigner extends string | AccountMeta<string> = string,
  TAccountState extends string | AccountMeta<string> = string,
  TAccountDelegate extends string | AccountMeta<string> = string,
  TAccountDepositorTokenAccount extends string | AccountMeta<string> = string,
  TAccountVault extends string | AccountMeta<string> = string,
  TAccountMint extends string | AccountMeta<string> = string,
  TAccountTokenProgram extends string | AccountMeta<string> =
    "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
  TAccountAssociatedTokenProgram extends string | AccountMeta<string> =
    "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",
  TAccountSystemProgram extends string | AccountMeta<string> =
    "11111111111111111111111111111111",
  TAccountEventAuthority extends string | AccountMeta<string> = string,
  TAccountProgram extends string | AccountMeta<string> = string,
  TRemainingAccounts extends readonly AccountMeta<string>[] = [],
> = Instruction<TProgram> &
  InstructionWithData<ReadonlyUint8Array> &
  InstructionWithAccounts<
    [
      TAccountSigner extends string
        ? WritableSignerAccount<TAccountSigner> &
            AccountSignerMeta<TAccountSigner>
        : TAccountSigner,
      TAccountState extends string
        ? WritableAccount<TAccountState>
        : TAccountState,
      TAccountDelegate extends string
        ? ReadonlyAccount<TAccountDelegate>
        : TAccountDelegate,
      TAccountDepositorTokenAccount extends string
        ? WritableAccount<TAccountDepositorTokenAccount>
        : TAccountDepositorTokenAccount,
      TAccountVault extends string
        ? WritableAccount<TAccountVault>
        : TAccountVault,
      TAccountMint extends string
        ? ReadonlyAccount<TAccountMint>
        : TAccountMint,
      TAccountTokenProgram extends string
        ? ReadonlyAccount<TAccountTokenProgram>
        : TAccountTokenProgram,
      TAccountAssociatedTokenProgram extends string
        ? ReadonlyAccount<TAccountAssociatedTokenProgram>
        : TAccountAssociatedTokenProgram,
      TAccountSystemProgram extends string
        ? ReadonlyAccount<TAccountSystemProgram>
        : TAccountSystemProgram,
      TAccountEventAuthority extends string
        ? ReadonlyAccount<TAccountEventAuthority>
        : TAccountEventAuthority,
      TAccountProgram extends string
        ? ReadonlyAccount<TAccountProgram>
        : TAccountProgram,
      ...TRemainingAccounts,
    ]
  >;

export type DepositInstructionData = {
  discriminator: ReadonlyUint8Array;
  depositor: Address;
  recipient: Address;
  inputToken: Address;
  outputToken: Address;
  inputAmount: bigint;
  outputAmount: ReadonlyUint8Array;
  destinationChainId: bigint;
  exclusiveRelayer: Address;
  quoteTimestamp: number;
  fillDeadline: number;
  exclusivityParameter: number;
  message: ReadonlyUint8Array;
};

export type DepositInstructionDataArgs = {
  depositor: Address;
  recipient: Address;
  inputToken: Address;
  outputToken: Address;
  inputAmount: number | bigint;
  outputAmount: ReadonlyUint8Array;
  destinationChainId: number | bigint;
  exclusiveRelayer: Address;
  quoteTimestamp: number;
  fillDeadline: number;
  exclusivityParameter: number;
  message: ReadonlyUint8Array;
};

export function getDepositInstructionDataEncoder(): Encoder<DepositInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", fixEncoderSize(getBytesEncoder(), 8)],
      ["depositor", getAddressEncoder()],
      ["recipient", getAddressEncoder()],
      ["inputToken", getAddressEncoder()],
      ["outputToken", getAddressEncoder()],
      ["inputAmount", getU64Encoder()],
      ["outputAmount", fixEncoderSize(getBytesEncoder(), 32)],
      ["destinationChainId", getU64Encoder()],
      ["exclusiveRelayer", getAddressEncoder()],
      ["quoteTimestamp", getU32Encoder()],
      ["fillDeadline", getU32Encoder()],
      ["exclusivityParameter", getU32Encoder()],
      ["message", addEncoderSizePrefix(getBytesEncoder(), getU32Encoder())],
    ]),
    (value) => ({ ...value, discriminator: DEPOSIT_DISCRIMINATOR }),
  );
}

export function getDepositInstructionDataDecoder(): Decoder<DepositInstructionData> {
  return getStructDecoder([
    ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
    ["depositor", getAddressDecoder()],
    ["recipient", getAddressDecoder()],
    ["inputToken", getAddressDecoder()],
    ["outputToken", getAddressDecoder()],
    ["inputAmount", getU64Decoder()],
    ["outputAmount", fixDecoderSize(getBytesDecoder(), 32)],
    ["destinationChainId", getU64Decoder()],
    ["exclusiveRelayer", getAddressDecoder()],
    ["quoteTimestamp", getU32Decoder()],
    ["fillDeadline", getU32Decoder()],
    ["exclusivityParameter", getU32Decoder()],
    ["message", addDecoderSizePrefix(getBytesDecoder(), getU32Decoder())],
  ]);
}

export function getDepositInstructionDataCodec(): Codec<
  DepositInstructionDataArgs,
  DepositInstructionData
> {
  return combineCodec(
    getDepositInstructionDataEncoder(),
    getDepositInstructionDataDecoder(),
  );
}

export type DepositAsyncInput<
  TAccountSigner extends string = string,
  TAccountState extends string = string,
  TAccountDelegate extends string = string,
  TAccountDepositorTokenAccount extends string = string,
  TAccountVault extends string = string,
  TAccountMint extends string = string,
  TAccountTokenProgram extends string = string,
  TAccountAssociatedTokenProgram extends string = string,
  TAccountSystemProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  signer: TransactionSigner<TAccountSigner>;
  state: Address<TAccountState>;
  delegate: Address<TAccountDelegate>;
  depositorTokenAccount?: Address<TAccountDepositorTokenAccount>;
  vault?: Address<TAccountVault>;
  mint: Address<TAccountMint>;
  tokenProgram?: Address<TAccountTokenProgram>;
  associatedTokenProgram?: Address<TAccountAssociatedTokenProgram>;
  systemProgram?: Address<TAccountSystemProgram>;
  eventAuthority?: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  depositor: DepositInstructionDataArgs["depositor"];
  recipient: DepositInstructionDataArgs["recipient"];
  inputToken: DepositInstructionDataArgs["inputToken"];
  outputToken: DepositInstructionDataArgs["outputToken"];
  inputAmount: DepositInstructionDataArgs["inputAmount"];
  outputAmount: DepositInstructionDataArgs["outputAmount"];
  destinationChainId: DepositInstructionDataArgs["destinationChainId"];
  exclusiveRelayer: DepositInstructionDataArgs["exclusiveRelayer"];
  quoteTimestamp: DepositInstructionDataArgs["quoteTimestamp"];
  fillDeadline: DepositInstructionDataArgs["fillDeadline"];
  exclusivityParameter: DepositInstructionDataArgs["exclusivityParameter"];
  message: DepositInstructionDataArgs["message"];
};

export async function getDepositInstructionAsync<
  TAccountSigner extends string,
  TAccountState extends string,
  TAccountDelegate extends string,
  TAccountDepositorTokenAccount extends string,
  TAccountVault extends string,
  TAccountMint extends string,
  TAccountTokenProgram extends string,
  TAccountAssociatedTokenProgram extends string,
  TAccountSystemProgram extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address = typeof SVM_SPOKE_PROGRAM_ADDRESS,
>(
  input: DepositAsyncInput<
    TAccountSigner,
    TAccountState,
    TAccountDelegate,
    TAccountDepositorTokenAccount,
    TAccountVault,
    TAccountMint,
    TAccountTokenProgram,
    TAccountAssociatedTokenProgram,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): Promise<
  DepositInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountState,
    TAccountDelegate,
    TAccountDepositorTokenAccount,
    TAccountVault,
    TAccountMint,
    TAccountTokenProgram,
    TAccountAssociatedTokenProgram,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >
> {
  // Program address.
  const programAddress = config?.programAddress ?? SVM_SPOKE_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    signer: { value: input.signer ?? null, isWritable: true },
    state: { value: input.state ?? null, isWritable: true },
    delegate: { value: input.delegate ?? null, isWritable: false },
    depositorTokenAccount: {
      value: input.depositorTokenAccount ?? null,
      isWritable: true,
    },
    vault: { value: input.vault ?? null, isWritable: true },
    mint: { value: input.mint ?? null, isWritable: false },
    tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },
    associatedTokenProgram: {
      value: input.associatedTokenProgram ?? null,
      isWritable: false,
    },
    systemProgram: { value: input.systemProgram ?? 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">;
  }
  if (!accounts.depositorTokenAccount.value) {
    accounts.depositorTokenAccount.value = await getProgramDerivedAddress({
      programAddress:
        "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" as Address<"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL">,
      seeds: [
        getAddressEncoder().encode(expectSome(args.depositor)),
        getAddressEncoder().encode(expectAddress(accounts.tokenProgram.value)),
        getAddressEncoder().encode(expectAddress(accounts.mint.value)),
      ],
    });
  }
  if (!accounts.vault.value) {
    accounts.vault.value = await getProgramDerivedAddress({
      programAddress:
        "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" as Address<"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL">,
      seeds: [
        getAddressEncoder().encode(expectAddress(accounts.state.value)),
        getAddressEncoder().encode(expectAddress(accounts.tokenProgram.value)),
        getAddressEncoder().encode(expectAddress(accounts.mint.value)),
      ],
    });
  }
  if (!accounts.associatedTokenProgram.value) {
    accounts.associatedTokenProgram.value =
      "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" as Address<"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL">;
  }
  if (!accounts.systemProgram.value) {
    accounts.systemProgram.value =
      "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">;
  }
  if (!accounts.eventAuthority.value) {
    accounts.eventAuthority.value = await findEventAuthorityPda();
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta(accounts.signer),
      getAccountMeta(accounts.state),
      getAccountMeta(accounts.delegate),
      getAccountMeta(accounts.depositorTokenAccount),
      getAccountMeta(accounts.vault),
      getAccountMeta(accounts.mint),
      getAccountMeta(accounts.tokenProgram),
      getAccountMeta(accounts.associatedTokenProgram),
      getAccountMeta(accounts.systemProgram),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getDepositInstructionDataEncoder().encode(
      args as DepositInstructionDataArgs,
    ),
    programAddress,
  } as DepositInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountState,
    TAccountDelegate,
    TAccountDepositorTokenAccount,
    TAccountVault,
    TAccountMint,
    TAccountTokenProgram,
    TAccountAssociatedTokenProgram,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type DepositInput<
  TAccountSigner extends string = string,
  TAccountState extends string = string,
  TAccountDelegate extends string = string,
  TAccountDepositorTokenAccount extends string = string,
  TAccountVault extends string = string,
  TAccountMint extends string = string,
  TAccountTokenProgram extends string = string,
  TAccountAssociatedTokenProgram extends string = string,
  TAccountSystemProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  signer: TransactionSigner<TAccountSigner>;
  state: Address<TAccountState>;
  delegate: Address<TAccountDelegate>;
  depositorTokenAccount: Address<TAccountDepositorTokenAccount>;
  vault: Address<TAccountVault>;
  mint: Address<TAccountMint>;
  tokenProgram?: Address<TAccountTokenProgram>;
  associatedTokenProgram?: Address<TAccountAssociatedTokenProgram>;
  systemProgram?: Address<TAccountSystemProgram>;
  eventAuthority: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
  depositor: DepositInstructionDataArgs["depositor"];
  recipient: DepositInstructionDataArgs["recipient"];
  inputToken: DepositInstructionDataArgs["inputToken"];
  outputToken: DepositInstructionDataArgs["outputToken"];
  inputAmount: DepositInstructionDataArgs["inputAmount"];
  outputAmount: DepositInstructionDataArgs["outputAmount"];
  destinationChainId: DepositInstructionDataArgs["destinationChainId"];
  exclusiveRelayer: DepositInstructionDataArgs["exclusiveRelayer"];
  quoteTimestamp: DepositInstructionDataArgs["quoteTimestamp"];
  fillDeadline: DepositInstructionDataArgs["fillDeadline"];
  exclusivityParameter: DepositInstructionDataArgs["exclusivityParameter"];
  message: DepositInstructionDataArgs["message"];
};

export function getDepositInstruction<
  TAccountSigner extends string,
  TAccountState extends string,
  TAccountDelegate extends string,
  TAccountDepositorTokenAccount extends string,
  TAccountVault extends string,
  TAccountMint extends string,
  TAccountTokenProgram extends string,
  TAccountAssociatedTokenProgram extends string,
  TAccountSystemProgram extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address = typeof SVM_SPOKE_PROGRAM_ADDRESS,
>(
  input: DepositInput<
    TAccountSigner,
    TAccountState,
    TAccountDelegate,
    TAccountDepositorTokenAccount,
    TAccountVault,
    TAccountMint,
    TAccountTokenProgram,
    TAccountAssociatedTokenProgram,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): DepositInstruction<
  TProgramAddress,
  TAccountSigner,
  TAccountState,
  TAccountDelegate,
  TAccountDepositorTokenAccount,
  TAccountVault,
  TAccountMint,
  TAccountTokenProgram,
  TAccountAssociatedTokenProgram,
  TAccountSystemProgram,
  TAccountEventAuthority,
  TAccountProgram
> {
  // Program address.
  const programAddress = config?.programAddress ?? SVM_SPOKE_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    signer: { value: input.signer ?? null, isWritable: true },
    state: { value: input.state ?? null, isWritable: true },
    delegate: { value: input.delegate ?? null, isWritable: false },
    depositorTokenAccount: {
      value: input.depositorTokenAccount ?? null,
      isWritable: true,
    },
    vault: { value: input.vault ?? null, isWritable: true },
    mint: { value: input.mint ?? null, isWritable: false },
    tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },
    associatedTokenProgram: {
      value: input.associatedTokenProgram ?? null,
      isWritable: false,
    },
    systemProgram: { value: input.systemProgram ?? 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">;
  }
  if (!accounts.associatedTokenProgram.value) {
    accounts.associatedTokenProgram.value =
      "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" as Address<"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL">;
  }
  if (!accounts.systemProgram.value) {
    accounts.systemProgram.value =
      "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">;
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta(accounts.signer),
      getAccountMeta(accounts.state),
      getAccountMeta(accounts.delegate),
      getAccountMeta(accounts.depositorTokenAccount),
      getAccountMeta(accounts.vault),
      getAccountMeta(accounts.mint),
      getAccountMeta(accounts.tokenProgram),
      getAccountMeta(accounts.associatedTokenProgram),
      getAccountMeta(accounts.systemProgram),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getDepositInstructionDataEncoder().encode(
      args as DepositInstructionDataArgs,
    ),
    programAddress,
  } as DepositInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountState,
    TAccountDelegate,
    TAccountDepositorTokenAccount,
    TAccountVault,
    TAccountMint,
    TAccountTokenProgram,
    TAccountAssociatedTokenProgram,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type ParsedDepositInstruction<
  TProgram extends string = typeof SVM_SPOKE_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    signer: TAccountMetas[0];
    state: TAccountMetas[1];
    delegate: TAccountMetas[2];
    depositorTokenAccount: TAccountMetas[3];
    vault: TAccountMetas[4];
    mint: TAccountMetas[5];
    tokenProgram: TAccountMetas[6];
    associatedTokenProgram: TAccountMetas[7];
    systemProgram: TAccountMetas[8];
    eventAuthority: TAccountMetas[9];
    program: TAccountMetas[10];
  };
  data: DepositInstructionData;
};

export function parseDepositInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>,
): ParsedDepositInstruction<TProgram, TAccountMetas> {
  if (instruction.accounts.length < 11) {
    // 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: {
      signer: getNextAccount(),
      state: getNextAccount(),
      delegate: getNextAccount(),
      depositorTokenAccount: getNextAccount(),
      vault: getNextAccount(),
      mint: getNextAccount(),
      tokenProgram: getNextAccount(),
      associatedTokenProgram: getNextAccount(),
      systemProgram: getNextAccount(),
      eventAuthority: getNextAccount(),
      program: getNextAccount(),
    },
    data: getDepositInstructionDataDecoder().decode(instruction.data),
  };
}
