import { NextRequest, NextResponse } from 'next/server';
import { postgresClient as pg } from '@/lib/services/postgres-client';

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const limit = Math.min(parseInt(searchParams.get('limit') ?? '200'), 1000);
    const level = searchParams.get('level') ?? '';
    const type = searchParams.get('type') ?? '';

    const conditions: string[] = [];
    const params: any[] = [];
    let paramIdx = 1;

    if (level) {
      conditions.push(`threat_level = $${paramIdx++}`);
      params.push(level);
    }
    if (type) {
      conditions.push(`event_type = $${paramIdx++}`);
      params.push(type);
    }

    const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
    params.push(limit);

    const result = await pg.query(`
      SELECT id, message_id, event_type, threat_level, url, file_name,
             verdict, actor_email, event_datetime
      FROM mimecast_threat_events
      ${where}
      ORDER BY event_datetime DESC NULLS LAST
      LIMIT $${paramIdx}
    `, params);

    return NextResponse.json({ threats: result.rows });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
