import type { Listing } from '@/lib/types'

const BASE = 'http://localhost:8000/api'

type RawListing = Omit<Listing, 'images' | 'closing_alerts_sent'> & {
  images: string | null
  closing_alerts_sent: string | null
}

export function parseListingResponse(raw: RawListing): Listing {
  return {
    ...raw,
    images: raw.images ? JSON.parse(raw.images) : [],
    closing_alerts_sent: raw.closing_alerts_sent ? JSON.parse(raw.closing_alerts_sent) : [],
  }
}

export async function fetchListings(limit = 100): Promise<Listing[]> {
  const res = await fetch(`${BASE}/listings?limit=${limit}`)
  if (!res.ok) throw new Error('Failed to fetch listings')
  const data: RawListing[] = await res.json()
  return data.map(parseListingResponse)
}

export async function deleteListing(id: number): Promise<void> {
  const res = await fetch(`${BASE}/listings/${id}`, { method: 'DELETE' })
  if (!res.ok) throw new Error('Failed to delete listing')
}

export async function deleteAllListings(): Promise<void> {
  const res = await fetch(`${BASE}/listings`, { method: 'DELETE' })
  if (!res.ok) throw new Error('Failed to clear listings')
}

export async function fetchCountdownSync(): Promise<Array<{ id: number; time_left_mins: number }>> {
  const res = await fetch(`${BASE}/listings/countdown-sync`)
  if (!res.ok) throw new Error('Failed to sync countdown')
  return res.json()
}

// Export endpoints — trigger as browser download, not fetch
export const getExportUrl = (format: 'csv' | 'json' | 'html') =>
  `${BASE}/export/${format}`
