import { useQuery } from '@tanstack/react-query'
import { useMatchDetail } from './useMatches'
import { propertyService } from '../services/propertyService'
import { needService } from '../services/needService'
import { futureSignalService } from '../services/futureSignalService'
import type { ItemResponse } from '../services/types'
import type { Property } from '../domain/property'
import type { Need } from '../domain/need'
import type { FutureSignal } from '../domain/futureSignal'

type Match = NonNullable<ReturnType<typeof useMatchDetail>['data']>

export function useMatchDetailData(matchId: string) {
  const { data: match, isLoading } = useMatchDetail(matchId)
  const isFuture = match?.resultType === 'FUTURE_AVAILABILITY'

  const { data: property = null } = useQuery<ItemResponse<Property | null>, Error, Property | null>({
    queryKey: ['property', match?.propertyId],
    queryFn: () => propertyService.getById(match!.propertyId),
    enabled: !!match && !isFuture,
    select: r => r.data ?? null,
  })

  const { data: need = null } = useQuery<ItemResponse<Need | null>, Error, Need | null>({
    queryKey: ['need', match?.needId],
    queryFn: () => needService.getById(match!.needId),
    enabled: !!match?.needId,
    select: r => r.data ?? null,
  })

  const { data: signal = null } = useQuery<FutureSignal | null>({
    queryKey: ['signal', match?.resultId],
    queryFn: async () => {
      // resultId may be a signal ID ('signal-002') or a property ID ('prop-006')
      const byId = await futureSignalService.getById(match!.resultId!)
      if (byId.data) return byId.data
      const byProp = await futureSignalService.getByProperty(match!.resultId!)
      return byProp.data[0] ?? null
    },
    enabled: !!match && isFuture && !!match.resultId,
  })

  return {
    match: match as Match | null | undefined,
    property,
    need,
    signal,
    isLoading,
    isFuture,
  }
}
