import { NextResponse } from 'next/server';

import { requireSuperAdmin, withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { revokeCrmInvite } from '@/lib/services/crm-invite.service';

// Invites are a global resource (no portId column). Revoking a foreign
// tenant's pending invite by id would be cross-tenant tampering;
// restrict to super-admins to match the listing endpoint.
export const DELETE = withAuth(
  withPermission('admin', 'manage_users', async (_req, ctx, params) => {
    try {
      requireSuperAdmin(ctx, 'admin.invitations.revoke');
      const id = params.id ?? '';
      await revokeCrmInvite(id, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
