export const dynamic = 'force-dynamic';

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

// GET /api/projects — List all user's projects
export async function GET() {
    const session = await auth();
    if (!session?.user?.id) {
        return NextResponse.json({ error: 'Non autorisé' }, { status: 401 });
    }

    const projects = await getDB().project.findMany({
        where: { userId: session.user.id },
        orderBy: { updatedAt: 'desc' },
        include: {
            _count: { select: { chapters: true, entities: true } },
        },
    });

    return NextResponse.json(projects);
}



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

    // Check plan limits
    const prisma = getDB();
    const user = await prisma.user.findUnique({
        where: { id: session.user.id },
        include: { subscriptionPlan: true }
    }) as any; // Cast to any to bypass Prisma type cache issues

    const limit = user?.subscriptionPlan?.maxProjects ?? 3;
    const planName = user?.subscriptionPlan?.displayName || 'Gratuit';
    const currentCount = await prisma.project.count({ where: { userId: session.user.id } });

    if (limit !== -1 && currentCount >= limit) {
        return NextResponse.json(
            { error: `Limite de ${limit} projets atteinte pour le plan ${planName}. Passez au plan supérieur !` },
            { status: 403 }
        );
    }

    const body = await request.json();

    const project = await prisma.project.create({
        data: {
            title: body.title || 'Nouveau Roman',
            author: body.author || session.user.name || 'Auteur',
            settings: body.settings || null,
            userId: session.user.id,
        },
    });

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