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

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

export async function GET(request) {
  let session;
  try {
    session = await requireSession(request);
    await requireFreshMembership(session, session.org_id);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    throw err;
  }
  const u = new URL(request.url);
  const limit = Math.min(500, Math.max(1, Number(u.searchParams.get('limit') || 100)));
  const type = u.searchParams.get('type') || null;
  // audit_logs has no agent_id column — agent filter applies to tool_egress only
  const agentId = u.searchParams.get('agent_id') || null;
  const since = u.searchParams.get('since') || null;

  const db = getDb();

  // P1-6: Scope audit_logs to the caller's org — mirrors audit-export scoping.
  // audit_logs: columns id, at, type, summary, status, meta — no agent_id
  const auditWhere = [];
  const auditArgs = [];
  if (session.org_id) { auditWhere.push('org_id = ?'); auditArgs.push(session.org_id); }
  if (type) { auditWhere.push('type = ?'); auditArgs.push(type); }
  if (since) { auditWhere.push('at >= ?'); auditArgs.push(since); }
  const auditSql = `SELECT id, at, type, summary, status, meta FROM audit_logs${auditWhere.length ? ' WHERE ' + auditWhere.join(' AND ') : ''} ORDER BY at DESC LIMIT ?`;
  const audit = db.prepare(auditSql).all(...auditArgs, limit);

  // tool_egress: columns id, tool_name, agent_id, host, method, status_code, bytes_out, bytes_in, duration_ms, error, at
  const egressWhere = [];
  const egressArgs = [];
  if (agentId) { egressWhere.push('agent_id = ?'); egressArgs.push(agentId); }
  if (since) { egressWhere.push('at >= ?'); egressArgs.push(since); }
  const egressSql = `SELECT id, tool_name, agent_id, host, method, status_code, bytes_out, bytes_in, duration_ms, error, at FROM tool_egress${egressWhere.length ? ' WHERE ' + egressWhere.join(' AND ') : ''} ORDER BY at DESC LIMIT ?`;
  const egress = db.prepare(egressSql).all(...egressArgs, limit);

  // distinct audit_log types for filter dropdown — also scoped to org
  const typesWhere = session.org_id ? 'WHERE org_id = ? AND type IS NOT NULL' : 'WHERE type IS NOT NULL';
  const typesArgs = session.org_id ? [session.org_id] : [];
  const types = db.prepare(`SELECT DISTINCT type FROM audit_logs ${typesWhere} ORDER BY type`).all(...typesArgs).map(r => r.type);

  return Response.json({ audit, egress, types });
}
