import { db } from "@/lib/prisma";
import { requireTeacher } from "@/lib/auth/requireTeacher";
import { notFound, redirect } from "next/navigation";
import TeacherEditCourseForm from "@/components/teacher/TeacherEditCourseForm";

export default async function CourseEditPage({ params }: { params: Promise<{ slug: string }> }) {
  const user = await requireTeacher();
  if (!user) redirect("/auth/login");

  const { slug } = await params;

  // Fetch Course + Modules + Lessons
  const course = await db.course.findUnique({
    where: { slug: slug },
    include: {
      modules: {
        orderBy: { orderIndex: "asc" },
        include: {
          lessons: {
            orderBy: { orderIndex: "asc" },
          },
        },
      },
    },
  });

  if (!course) notFound();

  // Security Check
  if (course.authorId !== user.id && user.role !== "SUPER_ADMIN") {
    return <div>No autorizado</div>;
  }

  // Transform Decimal to number for the UI component
  const courseData = {
    ...course,
    price: course.price.toNumber(),
  };

  return <TeacherEditCourseForm course={courseData} />;
}