import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { getSessionUser } from "@/lib/auth";
import { getPlaylistWithItems, getVideoDetail, listComments, listVideos } from "@/lib/data";
import { WatchView } from "@/components/watch-view";
import { ensureSeeded } from "@/lib/seed";

export const dynamic = "force-dynamic";

export async function generateMetadata({ params }: { params: Promise<{ id: string }> }): Promise<Metadata> {
  const { id } = await params;
  const video = await getVideoDetail(id);
  if (!video) return { title: "Video not found" };
  return {
    title: video.title,
    description: video.description.slice(0, 200),
    openGraph: {
      title: video.title,
      description: video.description.slice(0, 200),
      images: video.thumbnailUrl ? [video.thumbnailUrl] : undefined,
      type: "video.other",
    },
  };
}

export default async function WatchPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ list?: string; t?: string }>;
}) {
  await ensureSeeded();
  const { id } = await params;
  const { list } = await searchParams;
  const session = await getSessionUser();
  const video = await getVideoDetail(id, session?.user.id);
  if (!video) notFound();

  const isOwner = session?.channel?.id === video.channel.id;
  if (video.visibility === "private" && !isOwner) notFound();
  if (video.status !== "ready" && !isOwner) notFound();
  if (video.scheduledFor && video.scheduledFor.getTime() > Date.now() && !isOwner) notFound();

  const [related, comments, playlist] = await Promise.all([
    listVideos({ excludeId: id, sort: "recommended", limit: 12, category: video.categorySlug }),
    listComments(id, session?.user.id),
    list ? getPlaylistWithItems(list) : Promise.resolve(null),
  ]);

  return (
    <WatchView
      video={video}
      related={related}
      comments={comments}
      playlist={playlist ? { ...playlist, items: playlist.items } : null}
      isOwner={Boolean(isOwner)}
      signedIn={Boolean(session)}
    />
  );
}
