import type { Book } from './Book';

export async function getAllBooks(): Promise<Book[]> {
  const response = await fetch(`${import.meta.env.VITE_API_SERVER}/books`);
  if (!response.ok) {
    throw new Error('Anfrage fehlgeschlagen');
  }
  const data = await response.json();
  return data;
}

export async function deleteBook(id: number): Promise<void> {
  const response = await fetch(
    `${import.meta.env.VITE_API_SERVER}/books/${id}`,
    {
      method: 'DELETE',
    }
  );
  if (!response.ok) {
    throw new Error('Löschen fehlgeschlagen');
  }
}

export async function editBook(book: Book): Promise<Book> {
  const response = await fetch(
    `${import.meta.env.VITE_API_SERVER}/books/${book.id}`,
    {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(book),
    }
  );
  if (!response.ok) {
    throw new Error('Aktualisierung fehlgeschlagen');
  }
  const data = await response.json();
  return data;
}
