export const dynamic = 'force-dynamic';

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

// PUT /api/projects/[id]/workflow — Sync workflow (nodes + connections)
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 prisma = getDB();

    // Verify ownership
    const project = await prisma.project.findFirst({
        where: { id, userId: session.user.id },
    });
    if (!project) {
        return NextResponse.json({ error: 'Projet non trouvé' }, { status: 404 });
    }

    const { nodes, connections } = await request.json();

    // Replace all nodes and connections in a transaction
    await prisma.$transaction(async (tx) => {
        // Delete existing
        await tx.plotConnection.deleteMany({ where: { projectId: id } });
        await tx.plotNode.deleteMany({ where: { projectId: id } });

        // Create new nodes
        if (nodes && nodes.length > 0) {
            await tx.plotNode.createMany({
                data: nodes.map((n: any) => ({
                    id: n.id,
                    projectId: id,
                    x: n.x,
                    y: n.y,
                    title: n.title || '',
                    description: n.description || '',
                    color: n.color || '#ffffff',
                    type: n.type || 'story',
                })),
            });
        }

        // Create new connections
        if (connections && connections.length > 0) {
            await tx.plotConnection.createMany({
                data: connections.map((c: any) => ({
                    id: c.id,
                    projectId: id,
                    source: c.source,
                    target: c.target,
                })),
            });
        }
    });

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