import { NextRequest, NextResponse } from 'next/server';

import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getRecentErrors } from '@/lib/services/system-monitoring.service';

export const GET = withAuth(async (req: NextRequest, ctx) => {
  try {
    if (!ctx.isSuperAdmin) {
      return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
    }

    const url = new URL(req.url);
    const limit = Math.min(100, Math.max(1, parseInt(url.searchParams.get('limit') ?? '20', 10)));

    const errors = await getRecentErrors(limit);
    return NextResponse.json({ data: errors });
  } catch (error) {
    return errorResponse(error);
  }
});
