← back to Norma

app/api/intelligence/compute/route.ts

42 lines

import { NextRequest, NextResponse } from 'next/server';
import { requireRole } from '@/lib/require-role';
import { computeAllScores, type EntityType } from '@/lib/power-score';

const ALL_ENTITY_TYPES: EntityType[] = ['organization', 'foundation', 'politician', 'journalist'];

/**
 * POST /api/intelligence/compute
 * Body: { scope: 'all' | 'organization' | 'politician' | ... }
 * Triggers a (re)computation of power scores for the given scope.
 * Returns: { success: true, computed: { organization: N, politician: N, ... } }
 */
export async function POST(request: NextRequest) {
  const auth = requireRole(request, 'admin', 'staff');
  if (auth instanceof NextResponse) return auth;

  try {
    let body: { scope?: string } = {};
    try {
      body = await request.json();
    } catch {
      // Treat a missing or malformed body the same as { scope: 'all' }
    }

    const scope = body.scope || 'all';
    const types = scope === 'all'
      ? ALL_ENTITY_TYPES
      : [scope as EntityType];

    const results: Record<string, number> = {};
    for (const t of types) {
      const scores = await computeAllScores(t);
      results[t] = scores.length;
    }

    return NextResponse.json({ success: true, computed: results });
  } catch (err) {
    console.error('[api/intelligence/compute] POST error:', (err as Error).message);
    return NextResponse.json({ error: 'Failed to compute scores' }, { status: 500 });
  }
}