import { useMemo } from 'react'
import { useMatches, useMatchesByNeed } from './useMatches'
import { useProperties } from './useProperties'
import { useFutureSignals } from './useFutureSignals'
import { useSchattenmarktSignals } from './useSchattenmarktSignals'
import type {
  UnifiedMatchResult,
  VerifiedPortfolioResult,
  ExternalMarketResult,
  FutureAvailabilityResult,
} from '../domain/unifiedResult'

export function useUnifiedResults(needId?: string) {
  const allMatchesQuery = useMatches()
  const needMatchesQuery = useMatchesByNeed(needId ?? '')
  const propertiesQuery = useProperties()
  const signalsQuery = useFutureSignals()

  const matchesQuery = needId ? needMatchesQuery : allMatchesQuery

  const isLoading =
    matchesQuery.isLoading || propertiesQuery.isLoading || signalsQuery.isLoading
  const error = matchesQuery.error ?? propertiesQuery.error ?? signalsQuery.error

  const matches = matchesQuery.data ?? []
  const properties = propertiesQuery.data ?? []
  const signals = signalsQuery.data ?? []

  const schattenmarktSignals = useSchattenmarktSignals(properties)
  const allSignals = useMemo(() => [...signals, ...schattenmarktSignals], [signals, schattenmarktSignals])

  const data = useMemo((): UnifiedMatchResult[] => {
    return matches
      .flatMap((match): UnifiedMatchResult[] => {
        const refId = match.resultId ?? match.propertyId

        // Fast path: explicit FUTURE_AVAILABILITY on the match (no property lookup needed)
        if (match.resultType === 'FUTURE_AVAILABILITY') {
          const signal = allSignals.find(s => s.id === refId || s.propertyId === refId)
          if (!signal) return []
          return [{ matchId: match.id, needId: match.needId, matchScore: match.matchScore,
            resultType: 'FUTURE_AVAILABILITY', signal, match }]
        }

        const property = properties.find(p => p.id === refId)
        if (!property) return []

        // Use match.resultType if set; otherwise fall back to the property's own resultType.
        // This lets existing matches without an explicit resultType resolve correctly.
        const rt = match.resultType ?? property.resultType ?? 'VERIFIED_PORTFOLIO'

        if (rt === 'FUTURE_AVAILABILITY') {
          const signal = allSignals.find(s => s.id === refId || s.propertyId === refId)
          if (!signal) return []
          return [{ matchId: match.id, needId: match.needId, matchScore: match.matchScore,
            resultType: 'FUTURE_AVAILABILITY', signal, match }]
        }

        if (rt === 'EXTERNAL_MARKET' || rt === 'MAISON_WORK') {
          const result: ExternalMarketResult = {
            matchId: match.id,
            needId: match.needId,
            matchScore: match.matchScore,
            resultType: rt as 'EXTERNAL_MARKET' | 'MAISON_WORK',
            property,
            match,
          }
          return [result]
        }

        const result: VerifiedPortfolioResult = {
          matchId: match.id,
          needId: match.needId,
          matchScore: match.matchScore,
          resultType: 'VERIFIED_PORTFOLIO',
          property,
          match,
        }
        return [result]
      })
      .sort((a, b) => b.matchScore - a.matchScore)
  }, [matches, properties, allSignals])

  return { data, isLoading, error }
}
