← back to Norma
app/api/chat/route.ts
44 lines
import { NextRequest, NextResponse } from 'next/server';
import { requireRole } from '@/lib/require-role';
import { chatWithDraft } from '@/lib/chat';
import { checkRateLimit } from '@/lib/rate-limit';
/**
* POST /api/chat
* AI chat for iterating on a specific draft.
*
* Body: { draftId: string, message: string, history?: Array<{role, content}> }
*/
export async function POST(request: NextRequest) {
const auth = requireRole(request, 'admin', 'staff');
if (auth instanceof NextResponse) return auth;
const { limited, resetIn } = checkRateLimit(request);
if (limited) {
return NextResponse.json(
{ error: 'Rate limit exceeded', retryAfter: Math.ceil(resetIn / 1000) },
{ status: 429 },
);
}
try {
const { draftId, message, history } = await request.json();
if (!draftId || !message) {
return NextResponse.json(
{ error: 'draftId and message are required' },
{ status: 400 },
);
}
const result = await chatWithDraft(draftId, message, history || []);
return NextResponse.json(result);
} catch (err) {
console.error('[chat] Error:', (err as Error).message);
return NextResponse.json(
{ error: 'Chat request failed' },
{ status: 500 },
);
}
}