import type { FastifyInstance } from 'fastify';
import type { ErrorLogBuffer } from '../services/error-log-buffer.js';

/**
 * GET /api/v1/logs/errors?limit=N — recent mcpd error/fatal log records from
 * the in-memory ring buffer. RBAC: the `logs` operation (see mapUrlToPermission).
 */
export function registerLogRoutes(app: FastifyInstance, buffer: ErrorLogBuffer): void {
  app.get<{ Querystring: { limit?: string } }>('/api/v1/logs/errors', async (request) => {
    const raw = Number(request.query.limit);
    const limit = Number.isFinite(raw) && raw > 0 ? Math.min(raw, 500) : 50;
    return { errors: buffer.recent(limit) };
  });
}
