import { NextRequest, NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
import { requireStaffAuth } from '@/lib/auth';

const prisma = new PrismaClient();

export async function PUT(
    request: NextRequest,
    { params }: { params: Promise<{ id: string }> }
) {
    const { error, context } = await requireStaffAuth(request);
    if (error || !context) return error!;

    if (context.role !== 'curator') {
        return NextResponse.json(
            { error: 'Only curators can access this endpoint' },
            { status: 403 }
        );
    }

    try {
        const { id } = await params;
        const specialId = Number(id);
        const { songId, startTime, order } = await request.json();

        if (!specialId || Number.isNaN(specialId)) {
            return NextResponse.json({ error: 'Invalid special id' }, { status: 400 });
        }

        if (!songId || typeof startTime !== 'number') {
            return NextResponse.json({ error: 'Missing songId or startTime' }, { status: 400 });
        }

        // Prüfen, ob dieses Special dem Kurator zugeordnet ist
        const assignment = await prisma.curatorSpecial.findFirst({
            where: { curatorId: context.curator.id, specialId },
        });

        if (!assignment) {
            return NextResponse.json(
                { error: 'Forbidden: You are not allowed to edit this special' },
                { status: 403 }
            );
        }

        const specialSong = await prisma.specialSong.update({
            where: {
                specialId_songId: {
                    specialId,
                    songId,
                },
            },
            data: {
                startTime,
                order,
            },
            include: {
                song: true,
            },
        });

        return NextResponse.json(specialSong);
    } catch (e) {
        console.error('Error updating curator special song:', e);
        return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
    }
}


