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

const prisma = new PrismaClient();

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

        const special = await prisma.special.findUnique({
            where: { id: specialId },
            include: {
                songs: {
                    include: {
                        song: true
                    },
                    orderBy: {
                        order: 'asc'
                    }
                }
            }
        });

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

        return NextResponse.json(special);
    } catch (error) {
        console.error('Error fetching 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 { name, maxAttempts, unlockSteps, launchDate, endDate, curator } = await request.json();

        const special = await prisma.special.update({
            where: { id: specialId },
            data: {
                name,
                maxAttempts,
                unlockSteps: typeof unlockSteps === 'string' ? unlockSteps : JSON.stringify(unlockSteps),
                launchDate: launchDate ? new Date(launchDate) : null,
                endDate: endDate ? new Date(endDate) : null,
                curator: curator || null,
            }
        });

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