import { NextRequest, NextResponse } from 'next/server';
import { requireAuth } from '@/shared/auth/guards';
import { hasPermission } from '@/shared/admin/roles';
import { logAuditEvent } from '@/shared/admin/audit';
import type { Permission } from '@/shared/admin/permissions';

// --- ASA GENERATED START ---
// Admin guards — server-side permission checks for admin route handlers.
// Every admin endpoint MUST use requirePermission() — never UI-only checks.
// --- ASA GENERATED END ---

// --- USER CODE START ---

/**
 * Require a specific permission in an admin route handler.
 * Verifies auth + checks permission via RBAC engine.
 * Logs unauthorized access attempts to audit log.
 *
 * Usage:
 * ```ts
 * const { user, response } = await requirePermission(request, PERMISSIONS.USERS_LIST);
 * if (response) return response;
 * ```
 */
export async function requirePermission(
  request: NextRequest,
  permission: Permission,
): Promise<{
  user: { id: string; email: string } | null;
  response: NextResponse | null;
}> {
  const { user, response } = await requireAuth(request);
  if (response) return { user: null, response };

  const allowed = await hasPermission(user!.id, permission);

  if (!allowed) {
    // Log unauthorized access attempt
    await logAuditEvent({
      actor_id: user!.id,
      actor_email: user!.email,
      action: 'admin.access_denied',
      details: { permission, path: request.nextUrl.pathname },
    });

    return {
      user: null,
      response: NextResponse.json(
        { error: 'Insufficient permissions' },
        { status: 403 },
      ),
    };
  }

  return { user, response: null };
}

// --- USER CODE END ---
