import { useQuery } from '@tanstack/react-query'
import { propertyService } from '../services/propertyService'
import { matchService } from '../services/matchService'
import { futureSignalService } from '../services/futureSignalService'
import type { AssetType, ResultType } from '../domain/enums'
import { STALE_PROPERTIES, STALE_MATCHES, STALE_SIGNALS } from '../lib/constants'

interface PropertyFilter {
  assetType?: AssetType
  resultType?: ResultType
  city?: string
  minAreaSqm?: number
  maxRentPerSqm?: number
  organizationId?: string
}

export function useProperties(filter?: PropertyFilter) {
  return useQuery({
    queryKey: ['properties', filter ?? {}],
    queryFn: () => propertyService.getAll(filter),
    staleTime: STALE_PROPERTIES,
    select: (res) => res.data ?? [],
  })
}

export function useProperty(id: string) {
  return useQuery({
    queryKey: ['property', id],
    queryFn: () => propertyService.getById(id),
    staleTime: STALE_PROPERTIES,
    enabled: Boolean(id),
    select: (res) => res.data ?? null,
  })
}

export const usePropertyDetail = useProperty

export function usePropertyById(id: string | null) {
  return useQuery({
    queryKey: ['property', id],
    queryFn: () => propertyService.getById(id!),
    enabled: !!id,
    staleTime: STALE_PROPERTIES,
    select: (res) => res.data ?? null,
  })
}

export function usePropertyMatches(propertyId: string | null) {
  return useQuery({
    queryKey: ['property-matches', propertyId],
    queryFn: () => matchService.getMatchesForProperty(propertyId!),
    enabled: !!propertyId,
    staleTime: STALE_MATCHES,
    select: (res) => res.data ?? [],
  })
}

export function usePropertySignals(propertyId: string | null) {
  return useQuery({
    queryKey: ['property-signals', propertyId],
    queryFn: () => futureSignalService.getSignalsForProperty(propertyId!),
    enabled: !!propertyId,
    staleTime: STALE_SIGNALS,
    select: (res) => res.data ?? [],
  })
}
