export const dynamic = 'force-dynamic';

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

// POST /api/chapters — Create a chapter
export async function POST(request: NextRequest) {
    const session = await auth();
    if (!session?.user?.id) {
        return NextResponse.json({ error: 'Non autorisé' }, { status: 401 });
    }

    const body = await request.json();

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

    const chapter = await getDB().chapter.create({
        data: {
            title: body.title || 'Nouveau Chapitre',
            content: body.content || '',
            summary: body.summary || null,
            orderIndex: body.orderIndex || 0,
            projectId: body.projectId,
        },
    });

    return NextResponse.json(chapter, { status: 201 });
}
