import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { matchService } from '../services/matchService'
import { STALE_MATCHES } from '../lib/constants'

export function useMatches() {
  return useQuery({
    queryKey: ['matches'],
    queryFn: () => matchService.getAll(),
    staleTime: STALE_MATCHES,
    select: (res) => res.data ?? [],
  })
}

export function useMatchesByNeed(needId: string) {
  return useQuery({
    queryKey: ['matches', 'need', needId],
    queryFn: () => matchService.getByNeed(needId),
    staleTime: STALE_MATCHES,
    enabled: Boolean(needId),
    select: (res) => res.data ?? [],
  })
}

export function useMatchesByProperty(propertyId: string) {
  return useQuery({
    queryKey: ['matches', 'property', propertyId],
    queryFn: () => matchService.getByProperty(propertyId),
    staleTime: STALE_MATCHES,
    enabled: Boolean(propertyId),
    select: (res) => res.data ?? [],
  })
}

export function useApproveMatch() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (matchId: string) => matchService.approve(matchId, 'current-user'),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['matches'] })
    },
  })
}

export function useMatchDetail(id: string) {
  return useQuery({
    queryKey: ['match', id],
    queryFn: () => matchService.getById(id),
    staleTime: STALE_MATCHES,
    enabled: Boolean(id),
    select: (res) => res.data ?? null,
  })
}
