package com.atlassian.stash.internal.rest.util;

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.rest.BadRequestException;
import com.atlassian.bitbucket.rest.pull.RestPullRequestMergeConfig;
import com.atlassian.bitbucket.rest.pull.RestPullRequestMergeStrategy;

import javax.annotation.Nullable;
import java.util.Set;

import static com.atlassian.bitbucket.util.MoreCollectors.toImmutableSet;

/**
 * Utilities for merge strategies from REST requests.
 *
 */
public class RestMergeConfigUtils {

    private RestMergeConfigUtils() {
        throw new UnsupportedOperationException(RestMergeConfigUtils.class.getName() + " should not be instantiated");
    }

    public static Set<String> getMergeStrategyIds(Set<RestPullRequestMergeStrategy> strategies) {
        return strategies.stream()
                .map(RestPullRequestMergeStrategy::getId)
                .collect(toImmutableSet());
    }

    public static RestPullRequestMergeStrategy verifyDefaultStrategy(@Nullable RestPullRequestMergeConfig config,
                                                                     I18nService i18nService) {
        RestPullRequestMergeStrategy defaultStrategy = config == null ? null : config.getDefaultStrategy();
        if (defaultStrategy == null || defaultStrategy.getId() == null || !defaultStrategy.isEnabled()) {
            throw new BadRequestException(i18nService.getMessage(
                    "bitbucket.service.pullrequest.mergeconfig.invalid.default"));
        }
        return defaultStrategy;
    }
}
