import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export async function POST(
    request: Request,
    { params }: { params: Promise<{ id: string }> }
) {
    try {
        const { id } = await params;
        const specialId = parseInt(id);
        const { songId, startTime = 0, order } = await request.json();

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

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

export async function PUT(
    request: Request,
    { params }: { params: Promise<{ id: string }> }
) {
    try {
        const { id } = await params;
        const specialId = parseInt(id);
        const { songId, startTime, order } = await request.json();

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

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

export async function DELETE(
    request: Request,
    { params }: { params: Promise<{ id: string }> }
) {
    try {
        const { id } = await params;
        const specialId = parseInt(id);
        const { songId } = await request.json();

        await prisma.specialSong.delete({
            where: {
                specialId_songId: {
                    specialId,
                    songId
                }
            }
        });

        return NextResponse.json({ success: true });
    } catch (error) {
        console.error('Error removing song from special:', error);
        return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
    }
}
