// app/api/admin/videos/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(req: Request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email)
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const role = (session as any)?.user?.role ?? null;
    if (!(role === 'admin' || role === 'superadmin')) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    // Fetch all videos with their playlist and course info
    const videos = await prisma.video.findMany({
      include: {
        playlist: {
          include: {
            course: {
              select: {
                id: true,
                title: true,
              },
            },
          },
        },
        uploader: {
          select: {
            id: true,
            name: true,
            image: true,
          },
        },
        videoCourses: {
          include: { course: true },
        },
      },
      orderBy: { createdAt: 'desc' },
    });

    return NextResponse.json(videos);
  } catch (err: any) {
    console.error('get videos error', err);
    return NextResponse.json(
      { error: err?.message ?? 'server error' },
      { status: 500 }
    );
  }
}
