import { infiniteQueryOptions, queryOptions } from '@tanstack/react-query'
import { getFollowedTags } from 'src/lib/api'
import { activeProtocol } from 'src/lib/protocol'
import { queryKeys } from './keys'

// Hashtag operations now route through `activeProtocol()` — the adapter
// implementation per protocol owns the request shape, the filter semantics
// (`pf_type === 'photo'` on Pixelfed vs. `media_attachments[].type` on
// Mastodon), and the pagination invariants (omit `max_id` on the first page).
// `getFollowedTags` stays a direct `/api/v1/followed_tags` call — same shape
// on both servers, no divergence to mediate.

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

  feed: (id: string) =>
    infiniteQueryOptions({
      queryKey: queryKeys.hashtags.feed(id),
      queryFn: async ({ pageParam }) => {
        const page = await activeProtocol().fetchHashtagFeed(id, {
          cursor: { maxId: pageParam },
        })
        return page
      },
      initialPageParam: undefined as string | undefined,
      staleTime: 10 * 60 * 1000,
      gcTime: 60 * 60 * 1000,
      // The adapter already filtered the items + computed the next cursor;
      // surface them in the shape the consumer expects (flat list of
      // statuses per page) and the cursor for the next round.
      getNextPageParam: (lastPage) => lastPage.nextCursor?.maxId,
      select: (data) => ({
        ...data,
        pages: data.pages.map((p) => p.items),
      }),
    }),

  related: (id: string) =>
    queryOptions({
      queryKey: queryKeys.hashtags.related(id),
      queryFn: () => activeProtocol().fetchHashtagRelated(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,
    }),
}
