export const dynamic = 'force-dynamic';

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

// PUT /api/entities/[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 entity = await getDB().entity.findUnique({
        where: { id },
        include: { project: { select: { userId: true } } },
    });
    if (!entity || entity.project.userId !== session.user.id) {
        return NextResponse.json({ error: 'Non trouvé' }, { status: 404 });
    }

    const updated = await getDB().entity.update({
        where: { id },
        data: {
            ...(body.name !== undefined && { name: body.name }),
            ...(body.type !== undefined && { type: body.type }),
            ...(body.description !== undefined && { description: body.description }),
            ...(body.details !== undefined && { details: body.details }),
            ...(body.storyContext !== undefined && { storyContext: body.storyContext }),
            ...(body.attributes !== undefined && { attributes: body.attributes }),
            ...(body.customValues !== undefined && { customValues: body.customValues }),
        },
    });

    return NextResponse.json(updated);
}

// DELETE /api/entities/[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 entity = await getDB().entity.findUnique({
        where: { id },
        include: { project: { select: { userId: true } } },
    });
    if (!entity || entity.project.userId !== session.user.id) {
        return NextResponse.json({ error: 'Non trouvé' }, { status: 404 });
    }

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

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