← back to Patty

app/api/trending/route.ts

70 lines

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

export async function GET(request: NextRequest) {
  const user = verifyAuth(request);
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const url = new URL(request.url);
  const category = url.searchParams.get('category');

  let sql = `SELECT * FROM trending_topics`;
  const params: unknown[] = [];
  const conditions: string[] = [];

  if (category && category !== 'all') {
    params.push(category);
    conditions.push(`category = $${params.length}`);
  }

  if (conditions.length > 0) {
    sql += ` WHERE ` + conditions.join(' AND ');
  }

  sql += ` ORDER BY engagement_score DESC NULLS LAST, created_at DESC`;

  try {
    const result = await query(sql, params);
    return NextResponse.json({ rows: result.rows });
  } catch (err) {
    console.error('[api/trending] GET error:', (err as Error).message);
    return NextResponse.json({ error: 'Failed to fetch trending topics' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  const user = verifyAuth(request);
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  try {
    const body = await request.json();
    const { source, source_url, title, content, engagement_score, sentiment, category, tags } = body;

    if (!title || !source) {
      return NextResponse.json({ error: 'Title and source are required' }, { status: 400 });
    }

    const result = await query(
      `INSERT INTO trending_topics (source, source_url, title, content, engagement_score, sentiment, category, tags, expires_at)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW() + INTERVAL '7 days')
       RETURNING *`,
      [
        source,
        source_url || null,
        title,
        content || null,
        engagement_score || null,
        sentiment || null,
        category || null,
        tags || null,
      ]
    );

    return NextResponse.json({ row: result.rows[0] }, { status: 201 });
  } catch (err) {
    console.error('[api/trending] POST error:', (err as Error).message);
    return NextResponse.json({ error: 'Failed to create trending topic' }, { status: 500 });
  }
}