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

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

export async function fetchScoringRules(): Promise<ScoringRule[]> {
  const res = await fetch(`${BASE}/scoring-rules`)
  if (!res.ok) throw new Error('Failed to fetch scoring rules')
  return res.json()
}

export async function createScoringRule(
  signal: string,
  delta: number,
  notes?: string,
): Promise<ScoringRule> {
  const res = await fetch(`${BASE}/scoring-rules`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ signal, delta, notes }),
  })
  if (!res.ok) {
    const err = await res.json().catch(() => ({}))
    throw new Error(err.error || 'Failed to create rule')
  }
  return res.json()
}

export async function updateScoringRule(
  id: number,
  patch: Partial<Pick<ScoringRule, 'signal' | 'delta' | 'notes'>>,
): Promise<ScoringRule> {
  const res = await fetch(`${BASE}/scoring-rules/${id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(patch),
  })
  if (!res.ok) throw new Error('Failed to update rule')
  return res.json()
}

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