import { NextResponse } from 'next/server' import { auth } from '@/auth' import { prisma } from '@/lib/prisma' import { generateText } from 'ai' import { getChatProvider } from '@/lib/ai/factory' import { getSystemConfig } from '@/lib/config' export async function GET(req: Request) { try { const session = await auth() if (!session?.user?.id) { return new NextResponse('Unauthorized', { status: 401 }) } // Fetch the 5 most recently updated notes const notes = await prisma.note.findMany({ where: { userId: session.user.id }, orderBy: { updatedAt: 'desc' }, take: 5, select: { title: true, content: true } }) if (notes.length === 0) { return NextResponse.json({ insight: "Vous n'avez pas encore de notes pour générer des insights." }) } const context = notes.map((n, i) => `Note ${i + 1}:\nTitre: ${n.title || 'Sans titre'}\nContenu: ${n.content}`).join('\n\n') const config = await getSystemConfig() const provider = getChatProvider(config) const model = provider.getModel() const result = await generateText({ model, system: `Tu es un assistant IA d'analyse. Ton but est de lire les 5 dernières notes de l'utilisateur et d'en dégager un résumé synthétique ou 3 insights (idées clés/tendances). Sois concis, direct, et réponds en markdown. Le ton doit être professionnel.`, prompt: `Voici les 5 dernières notes de l'utilisateur:\n\n${context}` }) return NextResponse.json({ insight: result.text }) } catch (error) { console.error('Error generating insights:', error) return new NextResponse('Internal Server Error', { status: 500 }) } }