'use server';

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { Book } from './Book';

export async function saveBookAction(book: Book): Promise<string | void> {
  try {
    const response = await fetch('http://localhost:3001/books', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(book),
    });

    if (!response.ok) {
      throw new Error();
    }
  } catch {
    return 'Fehler beim Speichern.';
  }

  revalidatePath('/books');
  redirect('/books');
}
