'use server';

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { z } from 'zod/v4';
import type { $ZodErrorTree } from 'zod/v4/core';

const BookSchema = z.object({
  title: z.string().min(1, 'Titel ist erforderlich'),
  author: z.string().min(1, 'Autor ist erforderlich'),
  isbn: z.string().min(3, 'ISBN ist zu kurz'),
});

type Book = z.infer<typeof BookSchema>;

type SaveBookState = {
  error: $ZodErrorTree<Book> | { api: string[] } | null;
  values: Book | null;
};

export async function saveBookAction(
  prevState: SaveBookState,
  formData: FormData,
): Promise<SaveBookState> {
  const rawValues = Object.fromEntries(formData.entries());

  const parsed = BookSchema.safeParse(rawValues);

  if (!parsed.success) {
    const fieldErrors = z.treeifyError(parsed.error);

    return {
      error: fieldErrors,
      values: rawValues as Book,
    };
  }

  const response = await fetch('http://localhost:3001/books', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(parsed.data),
  });

  if (!response.ok) {
    return {
      error: { api: ['Fehler beim Speichern'] },
      values: parsed.data,
    };
  }

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