import { NextResponse } from 'next/server';

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

/**
 * GET /api/v1/admin/error-events/[requestId]
 *
 * Returns a single captured error_events row plus the heuristic
 * "likely culprit" classification. Permission: `admin.view_audit_log`.
 *
 * Tenant: super admins see any port; regular admins only see events
 * captured against their active port.
 */
export const GET = withAuth(
  withPermission('admin', 'view_audit_log', async (_req, ctx, params) => {
    try {
      const requestId = params.requestId;
      if (!requestId) throw new NotFoundError('Error event');

      const event = await getErrorEventById(requestId);
      if (!event) throw new NotFoundError('Error event');

      // Tenant scoping. A port_id of null on the row means the error
      // fired pre-port-resolve (login page, public form, etc.) - those
      // are visible to super admins only.
      if (!ctx.isSuperAdmin) {
        if (!event.portId || event.portId !== ctx.portId) {
          throw new NotFoundError('Error event');
        }
      }

      return NextResponse.json({
        data: {
          ...event,
          likelyCulprit: classifyError(event),
        },
      });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
