import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { listErrorEvents } from '@/lib/services/error-events.service';

/**
 * GET /api/v1/admin/error-events
 *
 * Paginated list of captured 5xx error_events rows. Powers the
 * super-admin error inspector at `/admin/errors`. Permission:
 * `admin.view_audit_log`.
 *
 * Query params:
 *   - statusCode: narrow to a single status (e.g. 500)
 *   - from / to:  ISO date strings; defaults to last 7 days server-side
 *   - limit:      defaults to 100; capped at 500 server-side
 *
 * Super admins see every port; regular admins are scoped to their port.
 */
export const GET = withAuth(
  withPermission('admin', 'view_audit_log', async (req, ctx) => {
    try {
      const url = new URL(req.url);
      const statusCode = url.searchParams.get('statusCode');
      const from = url.searchParams.get('from') ?? undefined;
      const to = url.searchParams.get('to') ?? undefined;
      const limitRaw = url.searchParams.get('limit');
      const limit = limitRaw ? Math.min(500, Math.max(1, Number(limitRaw))) : 100;

      const events = await listErrorEvents({
        portId: ctx.isSuperAdmin ? undefined : ctx.portId,
        statusCode: statusCode ? Number(statusCode) : undefined,
        from,
        to,
        limit,
      });
      return NextResponse.json({ data: events });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
