import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth-options";
import { listPublishedCourses } from "@/lib/course-queries";
import { CourseCard } from "@/components/course-card";
import { prisma } from "@/lib/prisma";

export default async function CoursesPage() {
  const session = await getServerSession(authOptions);
  const courses = await listPublishedCourses();

  let enrolledIds = new Set<string>();
  if (session?.user?.id) {
    const rows = await prisma.enrollment.findMany({
      where: { userId: session.user.id },
      select: { courseId: true },
    });
    enrolledIds = new Set(rows.map((r) => r.courseId));
  }

  return (
    <section className="section">
      <div className="container">
        <h1>Kursinhalte</h1>
        <p className="muted" style={{ marginBottom: "1.5rem" }}>
          Alle veröffentlichten Kurse – Einschreibung und Lektionen wie auf der Live-Akademie vorgesehen.
        </p>
        <div className="course-grid">
          {courses.map((c) => (
            <CourseCard key={c.id} course={c} enrolled={enrolledIds.has(c.id)} />
          ))}
        </div>
      </div>
    </section>
  );
}
