package com.atlassian.stash.internal.check;

import com.atlassian.plugin.PluginAccessor;
import com.atlassian.bitbucket.scm.ScmRequest;
import com.atlassian.bitbucket.scm.ScmRequestCheck;
import com.atlassian.bitbucket.scm.ScmRequestCheckModuleDescriptor;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static java.util.Collections.singletonList;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class ScmRequestCheckServiceImplTest {

    @Mock
    private LicensingCheck licensingCheck;
    @Mock
    private PluginAccessor pluginAccessor;
    @Mock
    private ScmRequest scmRequest;
    @Mock
    private ScmRequestCheck requestCheck;
    @Mock
    private ScmRequestCheckModuleDescriptor moduleDescriptor;

    private ScmRequestCheckServiceImpl checkService;

    @Before
    public void setUp() throws Exception {
        when(pluginAccessor.getEnabledModuleDescriptorsByClass(ScmRequestCheckModuleDescriptor.class))
                .thenReturn(singletonList(moduleDescriptor));
        when(moduleDescriptor.getModule()).thenReturn(requestCheck);
        checkService = new ScmRequestCheckServiceImpl(pluginAccessor, licensingCheck);
    }

    @Test
    public void testFailLicenseCheck() throws Exception {
        when(licensingCheck.check(isA(ScmRequest.class))).thenReturn(false);
        when(requestCheck.check(isA(ScmRequest.class))).thenReturn(true);
        assertFalse(checkService.checkActionAllowed(scmRequest));
        verifyNoMoreInteractions(requestCheck);
    }

    @Test
    public void testFailRequestCheck() throws Exception {
        when(licensingCheck.check(isA(ScmRequest.class))).thenReturn(true);
        when(requestCheck.check(isA(ScmRequest.class))).thenReturn(false);
        assertFalse(checkService.checkActionAllowed(scmRequest));
    }

    @Test
    public void testPass() throws Exception {
        when(licensingCheck.check(isA(ScmRequest.class))).thenReturn(true);
        when(requestCheck.check(isA(ScmRequest.class))).thenReturn(true);
        assertTrue(checkService.checkActionAllowed(scmRequest));
    }

}
