package com.atlassian.bitbucket.internal.connect.webhook;

import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.user.ServiceUser;
import com.atlassian.bitbucket.user.UserService;
import com.atlassian.webhooks.api.register.listener.WebHookListener;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.Optional;

import static org.junit.Assert.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class ConnectModuleWebHookListenerOwnerResolverTest {
    private static final String CONNECT_PLUGIN_ID = "some.connect.plugin";

    @InjectMocks
    private ConnectModuleWebHookListenerOwnerResolver connectResolver;
    @Mock
    private ServiceUser serviceUser;
    @Mock
    private UserService userService;

    @Test
    public void testCanResolveExistingConnectServiceUserForModuleWebhook() {
        WebHookListener listener = newModuleWebHookListener(CONNECT_PLUGIN_ID);

        when(userService.getServiceUserByName("addon_" + CONNECT_PLUGIN_ID, true)).thenReturn(serviceUser);

        Optional<ApplicationUser> applicationUser = connectResolver.resolveOwner(listener);
        assertTrue(applicationUser.isPresent());
        assertSame(serviceUser, applicationUser.get());

        verify(userService).getServiceUserByName("addon_" + CONNECT_PLUGIN_ID, true);
    }

    @Test
    public void testCantResolveNonExistantConnectServiceUserForModuleWebhook() {
        WebHookListener listener = newModuleWebHookListener(CONNECT_PLUGIN_ID);

        when(userService.getServiceUserByName(anyString(), eq(true))).thenReturn(null);

        Optional<ApplicationUser> applicationUser = connectResolver.resolveOwner(listener);
        assertFalse(applicationUser.isPresent());

        verify(userService).getServiceUserByName("addon_" + CONNECT_PLUGIN_ID, true);
    }

    private WebHookListener newModuleWebHookListener(String pluginId) {
        return WebHookListener.fromModuleDescriptor(pluginId).to("http://bitbucket.org").build();
    }
}