import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { needService } from '../services/needService'
import type { CreateNeedInput } from '../domain/need'

interface UseNeedsOptions {
  refetchOnMount?: boolean | 'always'
  gcTime?: number
}

export function useNeeds(options?: UseNeedsOptions) {
  return useQuery({
    queryKey: ['needs'],
    queryFn: () => needService.getAll(),
    select: (res) => res.data ?? [],
    ...options,
  })
}

export function useNeed(id: string) {
  return useQuery({
    queryKey: ['need', id],
    queryFn: () => needService.getById(id),
    enabled: Boolean(id),
    select: (res) => res.data ?? null,
  })
}

export const useNeedProfiles = useNeeds

export function useCreateNeed() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (input: CreateNeedInput) => needService.create(input),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['needs'] })
    },
  })
}
