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

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

export function useNeeds(options?: UseNeedsOptions) {
  const orgId = useSessionStore(s => s.currentUser?.organizationId)
  return useQuery({
    queryKey: ['needs', orgId],
    queryFn: () => needService.getAll({ organizationId: orgId }),
    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'] })
    },
  })
}

export function useUpdateNeed() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ id, ...data }: { id: string } & UpdateNeedInput) => needService.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['needs'] })
    },
  })
}

export function useArchiveNeed() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (id: string) => needService.update(id, { status: 'INACTIVE' }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['needs'] })
    },
  })
}
