import { useQuery } from '@tanstack/react-query'
import { search, type SearchResult } from '../services/api'
import { useFilterStore } from '../store/filterStore'

/**
 * Hybrid search hook — fires POST /photos/search when the user has a
 * non-empty search query. Returns results ranked by RRF (FTS + semantic).
 *
 * When `q` is empty, this hook is disabled and returns no data — the
 * normal usePhotosQuery takes over for browse mode.
 */
export function useSearchQuery() {
  const q = useFilterStore((s) => s.q)
  const tagIds = useFilterStore((s) => s.tagIds)
  const dateFrom = useFilterStore((s) => s.dateFrom)
  const dateTo = useFilterStore((s) => s.dateTo)

  const hasQuery = q.trim().length > 0

  return useQuery<SearchResult[]>({
    queryKey: ['search', q, tagIds, dateFrom, dateTo],
    queryFn: async () => {
      const resp = await search.query({
        q: q.trim(),
        filters: {
          tag_ids: tagIds.length > 0 ? tagIds : undefined,
          date_from: dateFrom ?? undefined,
          date_to: dateTo ?? undefined,
        },
        limit: 200,
      })
      return resp.results
    },
    enabled: hasQuery,
    staleTime: 30_000,
  })
}
