← back to Norma

app/api/data-explorer/frontpages/route.ts

68 lines

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

/**
 * GET /api/data-explorer/frontpages
 * Returns newspaper front pages from the newspaper_frontpages table.
 * Maps DB column names to the frontend interface:
 *   newspaper_name -> paper_name, top_headline -> headline, frontpage_url -> url
 */
export async function GET(request: NextRequest) {
  const auth = requireRole(request, 'admin', 'staff');
  if (auth instanceof NextResponse) return auth;

  try {
    const sp = request.nextUrl.searchParams;
    const limit = Math.min(parseInt(sp.get('limit') || '50', 10), 200);
    const offset = parseInt(sp.get('offset') || '0', 10);
    const country = sp.get('country');

    const conditions: string[] = [];
    const params: unknown[] = [];
    let idx = 1;

    if (country) {
      conditions.push(`country = $${idx++}`);
      params.push(country);
    }

    const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';

    params.push(limit, offset);

    const result = await query(
      `SELECT
         id,
         newspaper_name AS paper_name,
         country,
         top_headline AS headline,
         scraped_date,
         frontpage_url AS url,
         region,
         source_type,
         relevance_score
       FROM newspaper_frontpages
       ${where}
       ORDER BY scraped_date DESC, newspaper_name ASC
       LIMIT $${idx++} OFFSET $${idx++}`,
      params,
    );

    const countResult = await query(
      `SELECT COUNT(*) as total FROM newspaper_frontpages ${where}`,
      params.slice(0, -2),
    );

    return NextResponse.json({
      frontpages: result.rows,
      total: parseInt(countResult.rows[0]?.total ?? '0', 10),
      limit,
      offset,
    });
  } catch (err) {
    console.error('[data-explorer/frontpages] GET error:', (err as Error).message);
    return NextResponse.json({ error: 'Failed to load frontpages' }, { status: 500 });
  }
}