import { prisma } from "@/lib/prisma";
import { redirect } from "next/navigation";
import { notFound } from "next/navigation";

interface Props {
  params: Promise<{ slug: string }>;
}

export default async function CoursePage({ params }: Props) {
  const { slug } = await params;

  const course = await prisma.course.findUnique({
    where: { slug, published: true },
    include: {
      modules: {
        orderBy: { order: "asc" },
        include: {
          lessons: {
            where: { published: true },
            orderBy: { order: "asc" },
            select: { id: true },
            take: 1,
          },
        },
      },
    },
  });

  if (!course) notFound();

  // Redirect to the first published lesson
  for (const mod of course.modules) {
    if (mod.lessons.length > 0) {
      redirect(`/courses/${slug}/lessons/${mod.lessons[0].id}`);
    }
  }

  // No lessons yet — show placeholder
  return (
    <div className="p-10 text-center">
      <p className="text-4xl mb-4">📭</p>
      <p className="font-bold text-lg">Уроков пока нет</p>
      <p className="text-sm mt-1" style={{ color: "var(--muted-foreground)" }}>
        Курс в разработке. Загляните позже.
      </p>
    </div>
  );
}
