package com.atlassian.bitbucket.internal.mirroring.mirror;

import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.user.UserType;

import javax.annotation.Nonnull;

/**
 * Utility class to help map between service user names and mirror addons / upstream servers
 */
public class MirroringUserUtils {
    /**
     * Prefix for names of service users that map to an upstream server of a mirror
     */
    private static final String PREFIX_UPSTREAM_USERNAME = "upstream_";

    private MirroringUserUtils() {
    }

    @Nonnull
    public static String getUpstreamUsernameFor(@Nonnull String upstreamId) {
        return PREFIX_UPSTREAM_USERNAME + upstreamId;
    }

    public static boolean isUpstreamUsername(@Nonnull String name) {
        return name.startsWith(PREFIX_UPSTREAM_USERNAME);
    }

    public static boolean isUpstreamUser(ApplicationUser user) {
        return user != null && user.getType() == UserType.SERVICE && isUpstreamUsername(user.getName());
    }

    public static boolean isUpstreamUserFor(ApplicationUser user, @Nonnull String upstreamId) {
        return isUpstreamUser(user) && getUpstreamUsernameFor(upstreamId).equals(user.getName());
    }
}
