import type { TargetSite, SiteSelectors } from '@/lib/types'
const BASE = 'http://localhost:8000'

export const fetchSites = async (): Promise<TargetSite[]> => {
  const res = await fetch(`${BASE}/api/sites`)
  if (!res.ok) throw new Error('Failed to fetch sites')
  return res.json()
}

export const addSite = async (data: Partial<TargetSite>): Promise<TargetSite> => {
  const res = await fetch(`${BASE}/api/sites`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) })
  if (!res.ok) throw new Error('Failed to add site')
  return res.json()
}

export const updateSite = async (id: number, data: Partial<TargetSite>): Promise<void> => {
  const res = await fetch(`${BASE}/api/sites/${id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) })
  if (!res.ok) throw new Error('Failed to update site')
}

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

export const reorderSites = async (order: number[]): Promise<void> => {
  const res = await fetch(`${BASE}/api/sites/reorder`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ order }) })
  if (!res.ok) throw new Error('Failed to reorder sites')
}

export const adaptSite = async (id: number): Promise<void> => {
  const res = await fetch(`${BASE}/api/sites/${id}/adapt`, { method: 'POST' })
  if (!res.ok) throw new Error('Adapt failed')
}

export const fetchSiteSelectors = async (id: number): Promise<SiteSelectors | null> => {
  const res = await fetch(`${BASE}/api/sites/${id}/selectors`)
  if (res.status === 404) return null
  if (!res.ok) throw new Error('Failed to fetch selectors')
  return res.json()
}

export const deleteSiteSelectors = async (id: number): Promise<void> => {
  await fetch(`${BASE}/api/sites/${id}/selectors`, { method: 'DELETE' })
}
