import { notFound } from "next/navigation";
import { prisma } from "@/lib/db";
import { PageReader } from "@/components/PageReader";
import type { Metadata } from "next";

type Props = {
  params: Promise<{ slug: string; chapter: string }>;
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug, chapter } = await params;
  const chapterNum = parseInt(chapter, 10);
  if (isNaN(chapterNum)) return { title: "Not Found" };

  const manga = await prisma.manga.findUnique({ where: { slug } });
  if (!manga) return { title: "Not Found" };

  return {
    title: `${manga.title} — Ch. ${chapterNum}`,
    description: `Read chapter ${chapterNum} of ${manga.title}`,
  };
}

export default async function ChapterReaderPage({ params }: Props) {
  const { slug, chapter } = await params;
  const chapterNum = parseInt(chapter, 10);
  if (isNaN(chapterNum)) notFound();

  const manga = await prisma.manga.findUnique({
    where: { slug },
    include: {
      chapters: {
        orderBy: { number: "asc" },
        include: {
          pages: { orderBy: { number: "asc" } },
        },
      },
    },
  });

  if (!manga) notFound();

  const currentChapter = manga.chapters.find((c) => c.number === chapterNum);
  if (!currentChapter) notFound();

  const chapterIndex = manga.chapters.findIndex(
    (c) => c.number === chapterNum
  );
  const prevChapter =
    chapterIndex > 0 ? manga.chapters[chapterIndex - 1].number : null;
  const nextChapter =
    chapterIndex < manga.chapters.length - 1
      ? manga.chapters[chapterIndex + 1].number
      : null;

  const allChapters = manga.chapters.map((c) => ({
    number: c.number,
    title: c.title,
  }));

  return (
    <PageReader
      pages={currentChapter.pages}
      mangaSlug={manga.slug}
      mangaTitle={manga.title}
      chapterNumber={currentChapter.number}
      chapterTitle={currentChapter.title}
      prevChapter={prevChapter}
      nextChapter={nextChapter}
      chapters={allChapters}
    />
  );
}
