// app/api/playlists/[id]/route.ts import { NextResponse } from "next/server"; import { prisma } from "../../../../lib/prisma"; import { getServerSession } from "next-auth"; import { authOptions } from "../../../../lib/auth-options"; import { filterAccessibleVideos } from "../../../../lib/watch-progress"; export async function GET(req: Request, context: any) { try { // Unwrap params (Next may provide a Promise) let params = context?.params; if (typeof params?.then === "function") params = await params; const id = params?.id; if (!id) return NextResponse.json({ error: "Missing playlist id" }, { status: 400 }); const session = await getServerSession(authOptions); if (!session?.user?.email) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const user = await prisma.user.findUnique({ where: { email: session.user.email }, include: { enrollments: { select: { courseId: true } } }, }); if (!user) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const playlist = await prisma.playlist.findUnique({ where: { id }, include: { videos: { include: { uploader: { select: { id: true, name: true, image: true, }, }, videoCourses: { select: { courseId: true, exclusive: true } }, }, orderBy: { index: "asc" }, }, course: true, courses: { select: { courseId: true } }, }, }); if (!playlist) return NextResponse.json({ error: "Not found" }, { status: 404 }); // Enrolment in the primary course or any course the playlist is shared with. const userCourseIds = user.enrollments.map((e) => e.courseId); const playlistCourseIds = [playlist.courseId, ...playlist.courses.map((c) => c.courseId)]; if (!playlistCourseIds.some((courseId) => userCourseIds.includes(courseId))) { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); } // Hide videos reserved for courses this user is not in, as /api/playlists does. const visible = { ...playlist, videos: filterAccessibleVideos(playlist.videos, userCourseIds), }; return NextResponse.json({ playlist: visible }); } catch (err: any) { console.error("GET /api/playlists/[id] error:", err); return NextResponse.json({ error: "Server error" }, { status: 500 }); } }