import { infiniteQueryOptions, queryOptions } from '@tanstack/react-query'
import {
  getFollowedTags,
  getHashtagByName,
  getHashtagByNameFeed,
  getHashtagRelated,
} from 'src/lib/api'
import { nextCursorFromLowestId } from 'src/lib/pagination'
import { queryKeys } from './keys'

export const hashtagQueries = {
  byName: (id: string) =>
    queryOptions({
      queryKey: queryKeys.hashtags.byName(id),
      queryFn: () => getHashtagByName(id),
      staleTime: 10 * 60 * 1000,
      gcTime: 60 * 60 * 1000,
    }),

  feed: (id: string) =>
    infiniteQueryOptions({
      queryKey: queryKeys.hashtags.feed(id),
      queryFn: async ({ pageParam }) => {
        const data = await getHashtagByNameFeed(id, pageParam as string)
        return (
          data.data?.filter((p: any) => {
            return p.pf_type === 'photo' && p.media_attachments.length && !p.sensitive
          }) ?? []
        )
      },
      initialPageParam: undefined as string | undefined,
      staleTime: 10 * 60 * 1000,
      gcTime: 60 * 60 * 1000,
      getNextPageParam: (lastPage: any[]) => nextCursorFromLowestId(lastPage),
    }),

  related: (id: string) =>
    queryOptions({
      queryKey: queryKeys.hashtags.related(id),
      queryFn: () => getHashtagRelated(id),
      staleTime: 10 * 60 * 1000,
      gcTime: 60 * 60 * 1000,
    }),

  followed: () =>
    queryOptions({
      queryKey: queryKeys.hashtags.followed(),
      queryFn: getFollowedTags,
      staleTime: 5 * 60 * 1000,
      gcTime: 60 * 60 * 1000,
    }),
}
