import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { and, desc, eq } from "drizzle-orm";
import { db } from "@/db";
import { liveStreams, playlists } from "@/db/schema";
import { getSessionUser } from "@/lib/auth";
import { getChannelByHandle, getSubscriptionState, listVideos } from "@/lib/data";
import { ChannelView } from "@/components/channel-view";
import { ensureSeeded } from "@/lib/seed";

export const dynamic = "force-dynamic";

export async function generateMetadata({ params }: { params: Promise<{ handle: string }> }): Promise<Metadata> {
  const { handle } = await params;
  const channel = await getChannelByHandle(handle);
  if (!channel) return { title: "Channel not found" };
  return { title: channel.name, description: channel.description ?? `${channel.name} on PlayTube` };
}

export default async function ChannelPage({
  params,
  searchParams,
}: {
  params: Promise<{ handle: string }>;
  searchParams: Promise<{ tab?: string }>;
}) {
  await ensureSeeded();
  const { handle } = await params;
  const { tab } = await searchParams;
  const session = await getSessionUser();
  const channel = await getChannelByHandle(handle);
  if (!channel) notFound();

  const [videos, shorts, streams, channelPlaylists, subState] = await Promise.all([
    listVideos({ channelId: channel.id, sort: "recent", limit: 24 }),
    listVideos({ channelId: channel.id, isShort: true, sort: "recent", limit: 24 }),
    db.select().from(liveStreams).where(eq(liveStreams.channelId, channel.id)).orderBy(desc(liveStreams.startedAt)).limit(10),
    db
      .select()
      .from(playlists)
      .where(and(eq(playlists.ownerUserId, channel.userId), eq(playlists.visibility, "public")))
      .limit(12),
    getSubscriptionState(channel.id, session?.user.id),
  ]);

  return (
    <ChannelView
      channel={channel}
      videos={videos}
      shorts={shorts}
      streams={streams}
      playlists={channelPlaylists}
      subscribed={subState.subscribed}
      notify={subState.notify}
      isOwner={session?.user.id === channel.userId}
      initialTab={tab ?? "home"}
    />
  );
}
