/**
 * This file was generated by @pikku/cli@0.12.45
 */
import { useQuery, useInfiniteQuery, useMutation, type UseQueryOptions, type UseInfiniteQueryOptions, type UseMutationOptions, type InfiniteData } from '@tanstack/react-query'
import { usePikkuRPC } from '@pikku/react'
import type { FlattenedRPCMap } from '../../../../../../../../../../../tmp/lc/.pikku/rpc/pikku-rpc-wirings-map.gen.d.js'

type RPCInvoke = <Name extends keyof FlattenedRPCMap>(name: Name, data: FlattenedRPCMap[Name]['input']) => Promise<FlattenedRPCMap[Name]['output']>

export const usePikkuQuery = <Name extends keyof FlattenedRPCMap>(
  name: Name,
  data: FlattenedRPCMap[Name]['input'],
  options?: Omit<UseQueryOptions<FlattenedRPCMap[Name]['output'], Error>, 'queryKey' | 'queryFn'>
) => {
  const rpc = usePikkuRPC<{ invoke: RPCInvoke }>()
  return useQuery<FlattenedRPCMap[Name]['output'], Error>({
    queryKey: [name, data],
    queryFn: () => rpc.invoke(name, data),
    ...options,
  })
}

export const usePikkuMutation = <Name extends keyof FlattenedRPCMap>(
  name: Name,
  options?: Omit<UseMutationOptions<FlattenedRPCMap[Name]['output'], Error, FlattenedRPCMap[Name]['input']>, 'mutationFn'>
) => {
  const rpc = usePikkuRPC<{ invoke: RPCInvoke }>()
  return useMutation<FlattenedRPCMap[Name]['output'], Error, FlattenedRPCMap[Name]['input']>({
    mutationFn: (data) => rpc.invoke(name, data),
    ...options,
  })
}

type PaginatedKeys = {
  [K in keyof FlattenedRPCMap]: FlattenedRPCMap[K]['output'] extends { nextCursor?: string | null } ? K : never
}[keyof FlattenedRPCMap]

type InfiniteOpts<Name extends PaginatedKeys> = Omit<
  UseInfiniteQueryOptions<FlattenedRPCMap[Name]['output'], Error, InfiniteData<FlattenedRPCMap[Name]['output'], string | undefined>, readonly unknown[], string | undefined>,
  'queryKey' | 'queryFn' | 'getNextPageParam' | 'initialPageParam'
>

export const usePikkuInfiniteQuery = <Name extends PaginatedKeys>(
  name: Name,
  data: Omit<FlattenedRPCMap[Name]['input'], 'nextCursor'>,
  options?: InfiniteOpts<Name>
) => {
  const rpc = usePikkuRPC<{ invoke: RPCInvoke }>()
  return useInfiniteQuery({
    queryKey: [name, data] as const,
    queryFn: ({ pageParam }: { pageParam: string | undefined }) => rpc.invoke(name, { ...data, nextCursor: pageParam } as unknown as FlattenedRPCMap[Name]['input']),
    initialPageParam: undefined as string | undefined,
    getNextPageParam: (lastPage: FlattenedRPCMap[Name]['output']) => (lastPage as { nextCursor?: string }).nextCursor ?? undefined,
    ...options,
  })
}
