import { NextPage } from 'next';
import { readFile } from 'node:fs/promises';

type Book = {
  id: number;
  title: string;
  author: string;
  isbn: string;
  rating: number;
};

async function getBook(id: number): Promise<Book> {
  const content = await readFile('./data.json', 'utf-8');
  const books = JSON.parse(content).books as Book[];
  return books.find((book) => book.id === id)!;
}

const BookDetailPage: NextPage<PageProps<'/books/[id]'>> = async ({
  params,
}) => {
  const { id } = await params;
  const book = await getBook(parseInt(id, 10));

  return <h1>Details for {book.title}</h1>;
};

export default BookDetailPage;

export async function generateStaticParams(): Promise<{ id: string }[]> {
  const content = await readFile('./data.json', 'utf-8');
  const books = JSON.parse(content).books as Book[];
  return books.map((book) => ({ id: book.id.toString() }));
}
