import Link from "next/link";
import { redirect } from "next/navigation";
import { getSessionUser } from "@/lib/auth";
import { getProductRowBySlug } from "@/lib/products";
import { getLibraryContentsForUser } from "@/lib/purchases";

export const dynamic = "force-dynamic";

export default async function ConteudoPage({
  params,
}: {
  params: Promise<{ slug: string; contentId: string }>;
}) {
  const user = await getSessionUser();
  if (!user) redirect("/login");

  const { slug, contentId } = await params;
  const contents = await getLibraryContentsForUser(user.id, slug);
  const content = contents.find((c) => c.id === contentId);
  if (!content) redirect("/painel/biblioteca");

  const product = await getProductRowBySlug(slug);
  const title = content.title || product?.name || "Conteúdo";
  const viewUrl = `/api/library/${slug}/content/${contentId}/view`;
  const downloadUrl = `/api/library/${slug}/content/${contentId}/download`;

  return (
    <div className="ebook-reader">
      <header className="ebook-reader-bar">
        <Link href="/painel/biblioteca" className="b ghost sm">
          ← Biblioteca
        </Link>
        <h1>{title}</h1>
        <a href={downloadUrl} className="b lime sm">
          ⬇ Baixar
        </a>
      </header>
      {content.type === "video" ? (
        <video
          className="ebook-reader-frame"
          src={viewUrl}
          controls
          playsInline
          style={{ objectFit: "contain", background: "#000" }}
        />
      ) : (
        <iframe className="ebook-reader-frame" src={viewUrl} title={title} />
      )}
    </div>
  );
}
