import { useQuery } from '@tanstack/react-query'
import type { Status } from 'src/lib/api-types'
import { parseMobilizonEventUrl } from 'src/lib/mobilizon-enrichment'
import { halflightQueries } from 'src/lib/queries/halflight'

// Extracts a Mobilizon host + event uuid from a Status' pf_source. Prefers
// `pf_source.remote_url`; falls back to the canonical `uri` (which for remote
// statuses is the origin AP object) or `url`.
function mobilizonTarget(status: Status | undefined | null) {
  if (!status) return null
  if (status.pf_source?.platform !== 'mobilizon') return null
  const candidates = [status.pf_source?.remote_url, status.url, status.uri]
  for (const candidate of candidates) {
    if (!candidate) continue
    const parsed = parseMobilizonEventUrl(candidate)
    if (parsed) return parsed
  }
  return null
}

export function useEventEnrichment(status: Status | undefined | null) {
  const target = mobilizonTarget(status)
  return useQuery({
    ...halflightQueries.mobilizonEvent(target?.host ?? '', target?.uuid ?? ''),
    enabled: !!target,
  })
}
