const API_URL = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:5006/api"

async function fetchApi<T>(path: string, options?: RequestInit): Promise<T> {
  const res = await fetch(`${API_URL}${path}`, {
    headers: { "Content-Type": "application/json", ...options?.headers },
    ...options,
  })
  if (!res.ok) throw new Error(`API error: ${res.statusText}`)
  if (res.status === 204) return undefined as T
  return res.json()
}

import type { Category, Product, InventoryMovement } from "@/types"

export const api = {
  categories: {
    list: () => fetchApi<Category[]>("/categories"),
    get: (id: number) => fetchApi<Category>(`/categories/${id}`),
    create: (data: Omit<Category, "id" | "createdAt">) =>
      fetchApi<Category>("/categories", { method: "POST", body: JSON.stringify(data) }),
    update: (id: number, data: Category) =>
      fetchApi<void>(`/categories/${id}`, { method: "PUT", body: JSON.stringify(data) }),
    delete: (id: number) => fetchApi<void>(`/categories/${id}`, { method: "DELETE" }),
  },
  products: {
    list: () => fetchApi<Product[]>("/products"),
    get: (id: number) => fetchApi<Product>(`/products/${id}`),
    create: (data: Omit<Product, "id" | "createdAt" | "updatedAt" | "category">) =>
      fetchApi<Product>("/products", { method: "POST", body: JSON.stringify(data) }),
    update: (id: number, data: Product) =>
      fetchApi<void>(`/products/${id}`, { method: "PUT", body: JSON.stringify(data) }),
    delete: (id: number) => fetchApi<void>(`/products/${id}`, { method: "DELETE" }),
  },
  movements: {
    list: () => fetchApi<InventoryMovement[]>("/inventoryMovements"),
    byProduct: (productId: number) =>
      fetchApi<InventoryMovement[]>(`/inventoryMovements/product/${productId}`),
    create: (data: Omit<InventoryMovement, "id" | "createdAt" | "product">) =>
      fetchApi<InventoryMovement>("/inventoryMovements", {
        method: "POST",
        body: JSON.stringify(data),
      }),
  },
}
