// app/api/admin/manage-playlist-courses/route.ts
// Assign or remove a playlist from additional courses
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' };
}

// GET: Get all courses a playlist is assigned to
export async function GET(req: Request) {
  try {
    await checkAdmin();
    const { searchParams } = new URL(req.url);
    const playlistId = searchParams.get('playlistId');
    
    if (!playlistId) return NextResponse.json({ error: 'playlistId required' }, { status: 400 });

    const playlist = await prisma.playlist.findUnique({
      where: { id: playlistId },
      include: {
        course: true,
        courses: {
          include: { course: true },
        },
      },
    });

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

    // Return primary course + all additional courses
    const allCourses = [
      playlist.course,
      ...playlist.courses.map(cp => cp.course),
    ];

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

// POST: Assign playlist to an additional course
export async function POST(req: Request) {
  try {
    await checkAdmin();
    const { playlistId, courseId } = await req.json();
    
    if (!playlistId || !courseId) return NextResponse.json({ error: 'missing fields' }, { status: 400 });

    // Check if already assigned
    const existing = await prisma.coursePlaylist.findFirst({
      where: { playlistId, courseId },
    });

    if (existing) return NextResponse.json({ error: 'Already assigned' }, { status: 400 });

    const assignment = await prisma.coursePlaylist.create({
      data: { playlistId, courseId },
      include: { course: true },
    });

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

// DELETE: Remove playlist from a course
export async function DELETE(req: Request) {
  try {
    await checkAdmin();
    const { searchParams } = new URL(req.url);
    const playlistId = searchParams.get('playlistId');
    const courseId = searchParams.get('courseId');
    
    if (!playlistId || !courseId) return NextResponse.json({ error: 'missing fields' }, { status: 400 });

    // Don't allow deleting the primary course assignment
    const playlist = await prisma.playlist.findUnique({
      where: { id: playlistId },
    });

    if (!playlist) return NextResponse.json({ error: 'Playlist not found' }, { status: 404 });
    
    if (playlist.courseId === courseId) {
      return NextResponse.json({ error: 'Cannot remove primary course' }, { status: 400 });
    }

    await prisma.coursePlaylist.delete({
      where: {
        courseId_playlistId: { playlistId, courseId },
      },
    });

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