class EnvVarsBuilder {

    public static List<EnvVar> buildEnvVars(PipelineRun run, PipelineConfiguration configuration,
                                            Map<SystemParams, String> sysParams,
                                            Map<String, String> externalProperties) {
        Map<String, EnvVar> fullEnvVars = new HashMap<>();
        Map<String, String> envVarsMap = new HashMap<>();

        MapUtils.emptyIfNull(sysParams)
                .forEach((key, value) -> {
                    String name = key.getEnvName();
                    if (!key.isSecure()) {
                        envVarsMap.put(name, value);
                    }
                    fullEnvVars.put(name, new EnvVar(name, value, null));
                });

        MapUtils.emptyIfNull(externalProperties)
                .forEach((key, value) -> {
                    String name = getBashName(key);
                    envVarsMap.put(name, value);
                    fullEnvVars.put(name, new EnvVar(name, value, null));
                });

        MapUtils.emptyIfNull(configuration.getParameters())
                .entrySet()
                .stream()
                .map(parameter -> {
                    String name = parameter.getKey();
                    String value = parameter.getValue().getValue();
                    String type = parameter.getValue().getType();
                    return matchParameterToEnvVars(name, value, type, envVarsMap);
                })
                .flatMap(Arrays::stream)
                .forEach(e -> fullEnvVars.put(e.getName(), e));

        MapUtils.emptyIfNull(configuration.getEnvironmentParams())
                .forEach((name, value) -> {
                    envVarsMap.put(name, value);
                    fullEnvVars.put(name, new EnvVar(name, value, null));
                });

        run.setEnvVars(MapUtils.emptyIfNull(envVarsMap)
                .entrySet()
                .stream()
                .filter(e -> StringUtils.isNotBlank(e.getKey()))
                .filter(e -> SystemParams.SECURED_PREFIXES.stream().noneMatch(prefix -> e.getKey().startsWith(prefix)))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2)));
        return new ArrayList<>(fullEnvVars.values());
    }

    private  EnvVarsBuilder();

}