export const dynamic = 'force-dynamic';

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

// GET /api/projects/[id] — Get project with all related data
export async function GET(
    _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 project = await getDB().project.findFirst({
        where: { id, userId: session.user.id },
        include: {
            chapters: { orderBy: { orderIndex: 'asc' } },
            entities: true,
            ideas: { orderBy: { createdAt: 'desc' } },
            plotNodes: true,
            plotConnections: true,
        },
    });

    if (!project) {
        return NextResponse.json({ error: 'Projet non trouvé' }, { status: 404 });
    }

    return NextResponse.json(project);
}

// PUT /api/projects/[id] — Update a project
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();

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

    const project = await getDB().project.update({
        where: { id },
        data: {
            ...(body.title !== undefined && { title: body.title }),
            ...(body.author !== undefined && { author: body.author }),
            ...(body.settings !== undefined && { settings: body.settings }),
            ...(body.styleGuide !== undefined && { styleGuide: body.styleGuide }),
        },
    });

    return NextResponse.json(project);
}

// DELETE /api/projects/[id] — Delete project (cascades to all children)
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;

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

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

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