/**
 * GET /api/tool-egress — paginated list of external API call records.
 *
 * Query params:
 *   ?limit=100        default 100, max 500
 *   ?tool_name=       filter by exact tool name
 *   ?agent_id=        filter by agent ID (use "main" to match null/main-agent rows)
 *   ?host=            filter by exact host
 *   ?since=ISO        filter to rows with at >= ISO timestamp
 */

import { getDb } from '@/lib/db.js';
import { requireSession } from '@/lib/auth.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function GET(req) {
  try {
    await requireSession(req);
    const { searchParams } = new URL(req.url);

    const limit = Math.min(Math.max(Number(searchParams.get('limit') || 100), 1), 500);
    const toolName = searchParams.get('tool_name') || null;
    const agentIdParam = searchParams.get('agent_id') || null;
    const host = searchParams.get('host') || null;
    const since = searchParams.get('since') || null;

    const conditions = [];
    const params = [];

    if (toolName) {
      conditions.push('tool_name = ?');
      params.push(toolName);
    }

    if (agentIdParam === 'main') {
      conditions.push('agent_id IS NULL');
    } else if (agentIdParam) {
      conditions.push('agent_id = ?');
      params.push(agentIdParam);
    }

    if (host) {
      conditions.push('host = ?');
      params.push(host);
    }

    if (since) {
      conditions.push('at >= ?');
      params.push(since);
    }

    const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    const sql = `SELECT * FROM tool_egress ${where} ORDER BY at DESC LIMIT ?`;
    params.push(limit);

    const db = getDb();
    const rows = db.prepare(sql).all(...params);

    return Response.json({ ok: true, rows, count: rows.length });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    return Response.json({ ok: false, error: err.message }, { status: 500 });
  }
}
