import type { Metadata } from "next";
import { prisma } from "@/lib/prisma"
import { auth } from "@/lib/auth"
import { headers } from "next/headers"
import { redirect } from "next/navigation"
import ReaderWrapper from "@/components/reader/ReaderWrapper"

export async function generateMetadata({ params }: { params: Promise<{ bookId: string }> }): Promise<Metadata> {
  const { bookId } = await params;
  const book = await prisma.book.findUnique({ where: { id: bookId } });

  if (!book) {
    return {
      title: "Read | E-Library",
      description: "Read your borrowed digital book from the E-Library.",
    };
  }

  return {
    title: `Read ${book.title} | E-Library`,
    description: `Continue reading ${book.title} in the Federal Polytechnic Bali E-Library reader.`,
  };
}

export default async function ReadPage({ params }: { params: Promise<{ bookId: string }> }) {
  const { bookId } = await params

  const session = await auth.api.getSession({ headers: await headers() })
  if (!session) redirect("/login")

  const loan = await prisma.loan.findFirst({
    where: {
      userId: session.user.id,
      bookId,
      status: { in: ["ACTIVE", "OVERDUE"] }
    }
  });

  if (!loan) redirect("/library")

  const digitalAsset = await prisma.digitalAsset.findFirst({
    where: { bookId }
  });

  if (!digitalAsset) redirect("/library");

  const book = await prisma.book.findUnique({
    where: { id: bookId }
  });

  if (!book) redirect("/library");

  const fileUrl = `/api/read/${bookId}`;

  return <ReaderWrapper fileUrl={fileUrl} format={digitalAsset.format} title={book.title} />
}