// app/api/admin/playlist-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 { searchParams } = new URL(req.url);
    const playlistId = searchParams.get('playlistId');
    if (!playlistId)
      return NextResponse.json({ error: 'playlistId required' }, { status: 400 });

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

    const videos = await prisma.video.findMany({
      where: { playlistId },
      select: { id: true, title: true, thumbnail: true, index: true, durationSec: true },
      orderBy: { index: 'asc' },
    });

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