// app/api/admin/update-playlist/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 PATCH(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 });
    }

    const { playlistId, title } = await req.json();

    if (!playlistId) {
      return NextResponse.json(
        { error: 'playlistId required' },
        { status: 400 }
      );
    }

    if (!title || typeof title !== 'string' || title.trim().length === 0) {
      return NextResponse.json(
        { error: 'title required and must be non-empty' },
        { status: 400 }
      );
    }

    const updatedPlaylist = await prisma.playlist.update({
      where: { id: playlistId },
      data: { title: title.trim() },
    });

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