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

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

export const addKeyword = async (term: string, weight = 1): Promise<Keyword> => {
  const res = await fetch(`${BASE}/api/keywords`, {
    method: 'POST', headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ term, weight }),
  })
  if (!res.ok) throw new Error('Failed to add keyword')
  return res.json()
}

export const updateKeyword = async (id: number, data: Partial<Pick<Keyword, 'term' | 'weight' | 'ai_target' | 'min_price' | 'max_price'>>): Promise<void> => {
  const res = await fetch(`${BASE}/api/keywords/${id}`, {
    method: 'PUT', headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  })
  if (!res.ok) throw new Error('Failed to update keyword')
}

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

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