import { infiniteQueryOptions, queryOptions } from '@tanstack/react-query'
import {
  adminInstances,
  getAdminConfig,
  getAdminStats,
  getAdminUser,
  getAdminUsers,
  getAutospamReports,
  getModReports,
} from 'src/lib/api'
import type { LinkPaginatedResponse } from 'src/lib/pagination'
import { queryKeys } from './keys'

export const adminQueries = {
  stats: () =>
    queryOptions({
      queryKey: queryKeys.admin.stats(),
      queryFn: getAdminStats,
      staleTime: 60 * 1000,
      gcTime: 10 * 60 * 1000,
    }),

  config: () =>
    queryOptions({
      queryKey: queryKeys.admin.config(),
      queryFn: getAdminConfig,
      staleTime: 60 * 60 * 1000,
      gcTime: Number.POSITIVE_INFINITY,
    }),

  user: (id: string) =>
    queryOptions({
      queryKey: queryKeys.admin.user(id),
      queryFn: () => getAdminUser(id),
      staleTime: 5 * 60 * 1000,
      gcTime: 60 * 60 * 1000,
    }),

  reports: () =>
    queryOptions({
      queryKey: queryKeys.admin.modReports(),
      queryFn: getModReports,
      staleTime: 60 * 1000,
      gcTime: 10 * 60 * 1000,
    }),

  autospam: () =>
    queryOptions({
      queryKey: queryKeys.admin.autospam(),
      queryFn: getAutospamReports,
      staleTime: 60 * 1000,
      gcTime: 10 * 60 * 1000,
    }),

  users: () =>
    infiniteQueryOptions({
      queryKey: queryKeys.admin.users(),
      queryFn: ({ pageParam }) => getAdminUsers(pageParam),
      initialPageParam: null as string | null,
      staleTime: 60 * 1000,
      gcTime: 10 * 60 * 1000,
      getNextPageParam: (lastPage: LinkPaginatedResponse<unknown>) =>
        lastPage.nextPage ?? undefined,
    }),

  instances: (sort: string, sortBy: string) =>
    infiniteQueryOptions({
      queryKey: queryKeys.admin.instances(),
      queryFn: ({ pageParam }) =>
        adminInstances(sort, sortBy, {
          pageParam: pageParam ?? undefined,
        }),
      initialPageParam: null as string | null,
      staleTime: 60 * 1000,
      gcTime: 10 * 60 * 1000,
      getNextPageParam: (lastPage: LinkPaginatedResponse<unknown>) =>
        lastPage.nextPage ?? undefined,
      getPreviousPageParam: (lastPage: LinkPaginatedResponse<unknown>) =>
        lastPage.prevPage ?? undefined,
    }),
}
