class KeyService {

    public void deleteKey(String keyId, Boolean ignoreWarnings) throws KeyNotFoundException, ActionNotPossibleException,
            GlobalConfOutdatedException, UnhandledWarningsException {

        TokenInfo tokenInfo = tokenService.getTokenForKeyId(keyId);
        auditDataHelper.put(tokenInfo);
        KeyInfo keyInfo = getKey(tokenInfo, keyId);
        auditDataHelper.put(keyInfo);

        // verify permissions
        if (keyInfo.getUsage() == null) {
            securityHelper.verifyAuthority("DELETE_KEY");
        } else if (keyInfo.getUsage() == KeyUsageInfo.AUTHENTICATION) {
            securityHelper.verifyAuthority("DELETE_AUTH_KEY");
        } else if (keyInfo.getUsage() == KeyUsageInfo.SIGNING) {
            securityHelper.verifyAuthority("DELETE_SIGN_KEY");
        }

        // verify that action is possible
        possibleActionsRuleEngine.requirePossibleKeyAction(PossibleActionEnum.DELETE,
                tokenInfo, keyInfo);

        // unregister possible auth certs
        if (keyInfo.getUsage() == KeyUsageInfo.AUTHENTICATION) {
            // get list of auth certs to be unregistered
            List<CertificateInfo> unregister = keyInfo.getCerts().stream().filter(this::shouldUnregister)
                    .collect(Collectors.toList());

            if (!unregister.isEmpty() && !ignoreWarnings) {
                throw new UnhandledWarningsException(
                        new WarningDeviation(WARNING_AUTH_KEY_REGISTERED_CERT_DETECTED, keyId));
            }

            for (CertificateInfo certificateInfo : unregister) {
                unregisterAuthCert(certificateInfo);
            }
        }

        if (!auditDataHelper.dataIsForEvent(DELETE_ORPHANS)) {
            auditEventHelper.changeRequestScopedEvent(DELETE_KEY_FROM_TOKEN_AND_CONFIG);
        }

        // delete key needs to be done twice. First call deletes the certs & csrs
        try {
            signerProxyFacade.deleteKey(keyId, false);
            signerProxyFacade.deleteKey(keyId, true);
        } catch (CodedException e) {
            throw e;
        } catch (Exception other) {
            throw new SignerNotReachableException("delete key failed", other);
        }
    }

    @Autowired public  KeyService(TokenService tokenService, SignerProxyFacade signerProxyFacade,
            PossibleActionsRuleEngine possibleActionsRuleEngine,
            ManagementRequestSenderService managementRequestSenderService,
            SecurityHelper securityHelper,
            AuditDataHelper auditDataHelper,
            AuditEventHelper auditEventHelper,
            AuditEventLoggingFacade auditEventLoggingFacade);

}