import { Book } from '@/books/Book';
import DeleteButton from '@/books/DeleteButton';
import { NextPage } from 'next';
import { revalidatePath } from 'next/cache';

async function getBooks(): Promise<Book[]> {
  const response = await fetch('http://localhost:3001/books');
  return response.json();
}

const BooksPage: NextPage = async () => {
  async function deleteBook(id: number) {
    'use server';
    await fetch(`http://localhost:3001/books/${id}`, {
      method: 'DELETE',
    });
    revalidatePath('/books');
  }

  const books = await getBooks();

  return (
    <div>
      <h1>Bücher</h1>
      <ul>
        {books.map((book) => (
          <li key={book.id}>
            {book.title}
            <DeleteButton onDelete={deleteBook} id={book.id} />
          </li>
        ))}
      </ul>
    </div>
  );
};

export default BooksPage;
