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

// Always fetch fresh course data (no Full Route Cache) so save + router.refresh() shows updated level/status
export const dynamic = "force-dynamic";

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" },
            select: {
              id: true,
              title: true,
              description: true,
            },
          },
        },
      },
    },
  });

  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(),
  };

  // Key forces remount when course updates so uncontrolled inputs (level, status) show new defaultValues after save + router.refresh()
  return <TeacherEditCourseForm key={`${course.id}-${course.updatedAt.toISOString()}`} course={courseData} />;
}
