68 lines
2.3 KiB
TypeScript
68 lines
2.3 KiB
TypeScript
export const dynamic = 'force-dynamic';
|
|
|
|
import { NextRequest, NextResponse } from 'next/server';
|
|
import { auth } from '@/lib/auth';
|
|
import getDB from '@/lib/prisma';
|
|
import { generateStoryContent } from '@/lib/gemini';
|
|
|
|
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const session = await auth();
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: 'Non autorisé' }, { status: 401 });
|
|
}
|
|
|
|
const prisma = getDB();
|
|
|
|
// Check AI usage limit from DB
|
|
const dbUser = await prisma.user.findUnique({
|
|
where: { id: session.user.id },
|
|
include: { subscriptionPlan: true },
|
|
}) as any; // Bypass Prisma client types for this relation
|
|
|
|
if (!dbUser) {
|
|
return NextResponse.json({ error: 'Utilisateur non trouvé' }, { status: 404 });
|
|
}
|
|
|
|
const limit = dbUser.subscriptionPlan?.maxAiActions ?? 100;
|
|
const planName = dbUser.subscriptionPlan?.displayName || 'Gratuit';
|
|
|
|
if (limit !== -1 && dbUser.aiActionsUsed >= limit) {
|
|
return NextResponse.json(
|
|
{ error: `Limite de ${limit} actions IA atteinte pour le plan ${planName}. Passez au plan supérieur !` },
|
|
{ status: 403 }
|
|
);
|
|
}
|
|
|
|
const body = await request.json();
|
|
const { project, chapterId, prompt, user } = body;
|
|
|
|
if (!project || !prompt || !user) {
|
|
return NextResponse.json(
|
|
{ error: 'Missing required fields: project, prompt, user' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Pass real plan from DB to gemini for model selection
|
|
const userWithPlan = { ...user, subscription: { ...user.subscription, plan: dbUser.plan } };
|
|
const result = await generateStoryContent(project, chapterId || '', prompt, userWithPlan);
|
|
|
|
// Increment usage in DB
|
|
await prisma.user.update({
|
|
where: { id: session.user.id },
|
|
data: { aiActionsUsed: { increment: 1 } },
|
|
});
|
|
|
|
return NextResponse.json({ ...result, aiActionsUsed: dbUser.aiActionsUsed + 1 });
|
|
} catch (error) {
|
|
console.error('AI generate error:', error);
|
|
return NextResponse.json(
|
|
{ error: 'AI generation failed' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|