class SdxRetryService {

    public FlowIdentifier retrySdx(SdxCluster sdxCluster) {
        List<FlowLog> flowLogs = flowLogService.findAllByResourceIdOrderByCreatedDesc(sdxCluster.getId());
        if (FlowRetryUtil.isFlowPending(flowLogs)) {
            LOGGER.info("Retry cannot be performed, because there is already an active flow. Sdx name: {}", sdxCluster.getClusterName());
            throw new BadRequestException("Retry cannot be performed, because there is already an active flow.");
        }
        return FlowRetryUtil.getMostRecentFailedLog(flowLogs)
                .map(log -> FlowRetryUtil.getLastSuccessfulStateLog(log.getCurrentState(), flowLogs))
                .map(lastSuccessfulStateLog -> {
                    if (SDX_STACK_CREATION_IN_PROGRESS_EVENT.name().equals(lastSuccessfulStateLog.getNextEvent())) {
                        LOGGER.info("Last successful state was " + SDX_STACK_CREATION_IN_PROGRESS_STATE + ", so try a retry on stack");
                        try {
                            ThreadBasedUserCrnProvider.doAsInternalActor(() ->
                                    stackV4Endpoint.retry(0L, sdxCluster.getClusterName(), sdxCluster.getAccountId()));
                        } catch (BadRequestException e) {
                            LOGGER.info("Sdx retry failed on cloudbreak side, but try to restart the flow. Related exception: ", e);
                        }
                    }
                    LOGGER.info("Sdx flow restarted: " + lastSuccessfulStateLog);
                    flow2Handler.restartFlow(lastSuccessfulStateLog);
                    if (lastSuccessfulStateLog.getFlowChainId() != null) {
                        return new FlowIdentifier(FlowType.FLOW_CHAIN, lastSuccessfulStateLog.getFlowChainId());
                    } else {
                        return new FlowIdentifier(FlowType.FLOW, lastSuccessfulStateLog.getFlowId());
                    }
                })
                .orElseThrow(() -> new BadRequestException("Retry cannot be performed, because the last action was successful"));
    }

}