export const dynamic = 'force-dynamic';

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

// PUT /api/ideas/[id]
export async function PUT(
    request: NextRequest,
    { params }: { params: Promise<{ id: string }> }
) {
    const session = await auth();
    if (!session?.user?.id) {
        return NextResponse.json({ error: 'Non autorisé' }, { status: 401 });
    }

    const { id } = await params;
    const body = await request.json();

    const idea = await getDB().idea.findUnique({
        where: { id },
        include: { project: { select: { userId: true } } },
    });
    if (!idea || idea.project.userId !== session.user.id) {
        return NextResponse.json({ error: 'Non trouvé' }, { status: 404 });
    }

    const updated = await getDB().idea.update({
        where: { id },
        data: {
            ...(body.title !== undefined && { title: body.title }),
            ...(body.description !== undefined && { description: body.description }),
            ...(body.status !== undefined && { status: body.status }),
            ...(body.category !== undefined && { category: body.category }),
        },
    });

    return NextResponse.json(updated);
}

// DELETE /api/ideas/[id]
export async function DELETE(
    _request: NextRequest,
    { params }: { params: Promise<{ id: string }> }
) {
    const session = await auth();
    if (!session?.user?.id) {
        return NextResponse.json({ error: 'Non autorisé' }, { status: 401 });
    }

    const { id } = await params;

    const idea = await getDB().idea.findUnique({
        where: { id },
        include: { project: { select: { userId: true } } },
    });
    if (!idea || idea.project.userId !== session.user.id) {
        return NextResponse.json({ error: 'Non trouvé' }, { status: 404 });
    }

    await getDB().idea.delete({ where: { id } });

    return NextResponse.json({ success: true });
}
