import { apiFetch } from './client'

export interface ShoppingItem {
  id: string
  name: string
  amount?: number
  unit?: string
  checked: boolean
  recipe_id?: string
  recipe_title?: string
  created_at?: string
}

export interface ShoppingGroup {
  recipe_title: string
  recipe_id?: string
  items: ShoppingItem[]
}

function scopeQuery(scope?: string) {
  return scope ? `?scope=${scope}` : ''
}

export function fetchShopping(scope?: string) {
  return apiFetch<ShoppingGroup[]>(`/shopping${scopeQuery(scope)}`)
}

export function addFromRecipe(recipeId: string, scope?: string) {
  return apiFetch<{ added: number }>(`/shopping/from-recipe/${recipeId}${scopeQuery(scope)}`, { method: 'POST' })
}

export function addCustomItem(item: { name: string; amount?: number; unit?: string }, scope?: string) {
  return apiFetch<ShoppingItem>(`/shopping${scopeQuery(scope)}`, {
    method: 'POST',
    body: JSON.stringify(item),
  })
}

export function addItems(items: { name: string; amount?: number; unit?: string }[], scope?: string) {
  return apiFetch<{ added: number }>(`/shopping/batch${scopeQuery(scope)}`, {
    method: 'POST',
    body: JSON.stringify({ items }),
  })
}

export function toggleCheck(id: string) {
  return apiFetch<ShoppingItem>(`/shopping/${id}/check`, { method: 'PATCH' })
}

export function deleteItem(id: string) {
  return apiFetch<void>(`/shopping/${id}`, { method: 'DELETE' })
}

export function deleteAll(scope?: string) {
  return apiFetch<void>(`/shopping/all${scopeQuery(scope)}`, { method: 'DELETE' })
}

export function deleteChecked(scope?: string) {
  return apiFetch<void>(`/shopping/checked${scopeQuery(scope)}`, { method: 'DELETE' })
}
