← back to Norma

app/api/pulse/topics/route.ts

46 lines

/**
 * GET /api/pulse/topics
 * Returns aggregated topics from news_items tags.
 */

import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/db';

export async function GET(request: NextRequest) {
  // Public endpoint — aggregate topic data for Pulse feed (no PII)
  try {
    // Aggregate topics from tags array
    const result = await query(`
      SELECT
        tag AS title,
        tag AS id,
        COUNT(*) AS article_count,
        'topic' AS category,
        CASE
          WHEN COUNT(*) >= 10 THEN 'high'
          WHEN COUNT(*) >= 5 THEN 'medium'
          ELSE 'low'
        END AS urgency,
        0 AS avg_sentiment,
        NULL AS petition_suggestion,
        NULL AS petition_target,
        ARRAY[]::text[] AS geo_states,
        false AS is_dismissed,
        NULL AS description
      FROM news_items, UNNEST(tags) AS tag
      WHERE tags IS NOT NULL
      GROUP BY tag
      ORDER BY article_count DESC
      LIMIT 30
    `);

    return NextResponse.json({
      topics: result.rows,
      total: result.rows.length,
    });
  } catch (err) {
    console.error('[api/pulse/topics] error:', (err as Error).message);
    return NextResponse.json({ error: 'Failed to fetch topics' }, { status: 500 });
  }
}