package com.atlassian.stash.internal.user;

import com.atlassian.bitbucket.auth.HttpAuthenticationContext;
import com.atlassian.bitbucket.auth.HttpAuthenticationSuccessContext;
import com.atlassian.bitbucket.user.TestApplicationUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Matchers.same;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class RecentlyAccessedRepositoriesAuthenticationSuccessHandlerTest {

    @Mock
    private HttpAuthenticationSuccessContext context;
    @Mock
    private InternalRecentlyAccessedRepositoriesService recentlyAccessedRepositoriesService;
    @InjectMocks
    private RecentlyAccessedRepositoriesAuthenticationSuccessHandler handler;

    @Test
    public void testRepoAccessesTrimmedWhenUserAuthenticatesForm() throws Exception {
        verifyOnAuthenticationSuccessWithMethod(HttpAuthenticationContext.METHOD_FORM);
    }

    @Test
    public void testRepoAccessesTrimmedWhenUserAuthenticatesToken() throws Exception {
        verifyOnAuthenticationSuccessWithMethod(HttpAuthenticationContext.METHOD_TOKEN);
    }

    private void verifyOnAuthenticationSuccessWithMethod(String method) throws Exception {
        TestApplicationUser user = new TestApplicationUser("mruser");

        when(context.getMethod()).thenReturn(method);
        when(context.getUser()).thenReturn(user);

        handler.onAuthenticationSuccess(context);

        verify(recentlyAccessedRepositoriesService).trimForUser(same(user));
    }

    @Test
    public void testTrimNotAttemptedIfUserBasicAuth() throws Exception {
        when(context.getMethod()).thenReturn(HttpAuthenticationContext.METHOD_BASIC);
        handler.onAuthenticationSuccess(context);
        verify(context, never()).getUser();
    }
}
