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

async function checkAdmin() {
  const session = await getServerSession(authOptions);
  if (!session?.user?.email) throw { status: 401, message: 'Unauthorized' };
  const allowed = (process.env.ALLOWED_ADMINS || '').split(',').map(s=>s.trim()).filter(Boolean);
  if (allowed.length && !allowed.includes(session.user.email)) throw { status: 403, message: 'Forbidden' };
}

export async function POST(req: Request) {
  try {
    await checkAdmin();
    const { title, courseId, additionalCourseIds } = await req.json();
    if (!title || !courseId) return NextResponse.json({ error: 'missing fields' }, { status: 400 });

    const playlist = await prisma.playlist.create({
      data: {
        title,
        courseId,
        // Create CoursePlaylist mappings for additional courses
        courses: {
          create: (additionalCourseIds || []).map((cid: string) => ({
            courseId: cid,
          })),
        },
      },
      include: {
        courses: {
          include: { course: true },
        },
      },
    });
    return NextResponse.json({ playlist });
  } catch (err: any) {
    console.error(err);
    return NextResponse.json({ error: err?.message ?? 'server' }, { status: err?.status ?? 500 });
  }
}
