// app/api/videos/latest/route.ts
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth-options';
import { prisma } from '@/lib/prisma';

export async function GET() {
  try {
    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 },
    });

    if (!user) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    // Get all courses the user is enrolled in
    const enrolledCourses = await prisma.enrollment.findMany({
      where: { userId: user.id },
      select: { courseId: true },
    });

    const enrolledCourseIds = enrolledCourses.map((e) => e.courseId);

    if (enrolledCourseIds.length === 0) {
      return NextResponse.json({ videos: [] });
    }

    // Get the latest 10 videos from those courses
    // Videos can be in playlists that belong to enrolled courses
    const videos = await prisma.video.findMany({
      where: {
        playlist: {
          OR: [
            { courseId: { in: enrolledCourseIds } },
            {
              courses: {
                some: { courseId: { in: enrolledCourseIds } },
              },
            },
          ],
        },
      },
      select: {
        id: true,
        title: true,
        durationSec: true,
        thumbnail: true,
        createdAt: true,
        uploader: {
          select: {
            id: true,
            name: true,
            image: true,
          },
        },
        playlist: {
          select: {
            id: true,
            title: true,
          },
        },
      },
      orderBy: { createdAt: 'desc' },
      take: 10,
    });

    return NextResponse.json({ videos });
  } catch (err: any) {
    console.error('GET /api/videos/latest error', err);
    return NextResponse.json(
      { error: err?.message ?? 'Server error' },
      { status: 500 }
    );
  }
}
