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

import com.atlassian.bitbucket.AuthorisationException;
import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.permission.Permission;
import com.atlassian.bitbucket.permission.PermissionValidationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;

@Component
public class MirroringValidationHelper {

    private final I18nService i18nService;
    private final MirrorAuthenticationContext mirrorAuthenticationContext;
    private final PermissionValidationService permissionValidationService;

    @Autowired
    public MirroringValidationHelper(I18nService i18nService,
                                     @Qualifier("defaultMirrorAuthenticationContext") MirrorAuthenticationContext mirrorAuthenticationContext,
                                     PermissionValidationService permissionValidationService) {
        this.i18nService = i18nService;
        this.mirrorAuthenticationContext = mirrorAuthenticationContext;
        this.permissionValidationService = permissionValidationService;
    }

    public void checkIsUpstreamUser(@Nonnull String upstreamId) {
        if (!isAuthenticatedAsUpstream(upstreamId)) {
            throw throwNotPermitted();
        }
    }

    public void checkIsUpstreamUserOrAdmin(@Nonnull String upstreamId) {
        if (!isAuthenticatedAsUpstream(upstreamId)) {
            permissionValidationService.validateForGlobal(Permission.ADMIN);
        }
    }

    private boolean isAuthenticatedAsUpstream(String upstreamId) {
        return mirrorAuthenticationContext.getCurrentUpstreamUser()
                .map(user -> MirroringUserUtils.isUpstreamUserFor(user, upstreamId))
                .orElse(false);
    }

    private AuthorisationException throwNotPermitted() {
        throw new AuthorisationException(i18nService.createKeyedMessage("bitbucket.mirroring.operation.not.allowed"));
    }
}
