export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import getDB from '@/lib/prisma';
import { transformTextServer } 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 type cache

        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 { text, mode, context, user } = body;

        if (!text || !mode || !user) {
            return NextResponse.json(
                { error: 'Missing required fields: text, mode, user' },
                { status: 400 }
            );
        }

        const result = await transformTextServer(text, mode, context || '', user);

        // Increment usage in DB
        await prisma.user.update({
            where: { id: session.user.id },
            data: { aiActionsUsed: { increment: 1 } },
        });

        return NextResponse.json({ text: result, aiActionsUsed: dbUser.aiActionsUsed + 1 });
    } catch (error) {
        console.error('AI transform error:', error);
        return NextResponse.json(
            { error: 'AI transformation failed' },
            { status: 500 }
        );
    }
}
