import { useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useHeapsQuery } from './useHeapsQuery'
import { heaps as heapsApi } from '../services/api'

const EMPTY_SET: ReadonlySet<string> = new Set()

/**
 * Returns the photo ids that belong to the active heap as a Set, plus the
 * active heap itself. Used by PhotoThumbnail to render the basket affordance
 * and by the P shortcut to decide between add vs remove.
 *
 * If no heap is active, the Set is empty (and shared across renders).
 */
export function useActiveHeapMembers(): {
  activeHeap: ReturnType<typeof useHeapsQuery>['data'] extends (infer T)[] | undefined
    ? T | null
    : never
  memberIds: ReadonlySet<string>
} {
  const { data: heaps } = useHeapsQuery()
  const activeHeap = heaps?.find((h) => h.is_active) ?? null

  const { data: ids } = useQuery({
    queryKey: ['heap-photo-ids', activeHeap?.id],
    queryFn: () => heapsApi.photoIds(activeHeap!.id),
    enabled: !!activeHeap,
    staleTime: 30_000,
  })

  const memberIds = useMemo(
    () => (ids ? new Set(ids) : EMPTY_SET),
    [ids]
  )

  return { activeHeap: activeHeap as any, memberIds }
}

export const ACTIVE_HEAP_MEMBERS_QUERY_KEY_PREFIX = ['heap-photo-ids'] as const
