package com.atlassian.stash.internal.web.filters;

import com.atlassian.bitbucket.auth.AuthenticationContext;
import com.atlassian.bitbucket.experimental.request.ExperimentalRequestContext;
import com.atlassian.bitbucket.request.RequestManager;
import com.atlassian.stash.internal.user.InternalNormalUser;
import com.atlassian.stash.internal.web.HttpRequestInfoHelper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

import javax.servlet.ServletException;
import java.io.IOException;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class AuthenticationAttributeFilterTest {

    @Mock
    private AuthenticationContext authenticationContext;
    @InjectMocks
    private AuthenticationAttributeFilter filter;
    @Mock
    private HttpRequestInfoHelper helper;
    @Mock
    private ExperimentalRequestContext requestContext;
    @Mock
    private RequestManager requestManager;

    @Before
    public void setUp() throws Exception {
        when(requestManager.getRequestContext()).thenReturn(requestContext);
    }

    @Test
    public void testAnonymous() throws Exception {
        checkFilter(null);
    }

    @Test
    public void testLogged() throws Exception {
        InternalNormalUser user = new InternalNormalUser.Builder().name("test").build();
        when(authenticationContext.getCurrentUser()).thenReturn(user);

        checkFilter("test");

        verify(requestContext).setAuthenticatedUser(user);
    }

    private void checkFilter(String expected) throws ServletException, IOException {
        final MockHttpServletResponse response = new MockHttpServletResponse();
        filter.doFilterInternal(new MockHttpServletRequest(), response, new MockFilterChain());
        assertEquals(expected, response.getHeader(AuthenticationAttributeFilter.X_AUSERNAME));
    }
}
