← back to Norma

app/api/news/detect-mentions/route.ts

57 lines

import { NextRequest, NextResponse } from 'next/server';
import { requireRole } from '@/lib/require-role';
import { getOrgId } from '@/lib/orgId';
import { batchDetectMentions } from '@/lib/detect-mentions';

/**
 * POST /api/news/detect-mentions
 * Run employee/org name detection on news articles.
 *
 * Body (optional):
 *   { articleIds?: string[], useGemini?: boolean }
 *
 * - If articleIds provided, run detection on those specific articles
 * - Otherwise, run on all articles from last 7 days without mentions
 * - useGemini: enable Gemini fallback for fuzzy matching (default: false)
 */
export async function POST(request: NextRequest) {
  const auth = requireRole(request, 'admin', 'staff');
  if (auth instanceof NextResponse) return auth;

  try {
    let articleIds: string[] | undefined;
    let useGemini = false;

    // Parse optional body
    const contentType = request.headers.get('content-type') ?? '';
    if (contentType.includes('application/json')) {
      try {
        const body = await request.json();
        if (Array.isArray(body.articleIds)) {
          articleIds = body.articleIds.filter((id: unknown) => typeof id === 'string');
        }
        if (typeof body.useGemini === 'boolean') {
          useGemini = body.useGemini;
        }
      } catch {
        // Non-JSON or empty body — use defaults
      }
    }

    const orgId = auth.role === 'admin' ? getOrgId(request) : auth.orgId;
    const result = await batchDetectMentions(articleIds, useGemini, orgId);

    return NextResponse.json({
      success: true,
      message: `Processed ${result.processed} articles. Found mentions in ${result.withMentions} (${result.totalMentions} total mentions).`,
      ...result,
    });
  } catch (err) {
    console.error('[api/news/detect-mentions] Error:', (err as Error).message);
    return NextResponse.json(
      { error: `Detection failed: ${(err as Error).message}` },
      { status: 500 },
    );
  }
}