package com.atlassian.stash.internal.idx;

import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.repository.RepositoryService;
import com.atlassian.bitbucket.user.DummySecurityService;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

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

@RunWith(MockitoJUnitRunner.class)
public class HierarchyIndexerTest {
    private static final int REPO1_ID = 1212;
    private static final int REPO2_ID = 3299;

    @Mock
    private CommitIndexingService indexingService;
    @Mock
    private Repository repository1;
    @Mock
    private Repository repository2;
    @Mock
    private RepositoryService repositoryService;

    private HierarchyIndexer indexer;

    @Before
    public void setup() {
        when(repository1.getId()).thenReturn(REPO1_ID);
        when(repositoryService.getById(REPO1_ID)).thenReturn(repository1);
        when(repository2.getId()).thenReturn(REPO2_ID);
        when(repositoryService.getById(REPO2_ID)).thenReturn(repository2);

        indexer = new HierarchyIndexer(indexingService, repositoryService, new DummySecurityService());
    }

    @Test
    public void testIndexing() {
        indexer.process("hierarchy", Lists.newArrayList(requestFor(REPO1_ID)));

        verify(indexingService).indexRepository(repository1);
    }

    @Test
    public void testIndexingExceptionIsHandled() {
        doThrow(IllegalStateException.class).when(indexingService).indexRepository(repository1);

        indexer.process("hierarchy", Lists.newArrayList(requestFor(REPO1_ID), requestFor(REPO2_ID)));

        verify(indexingService).indexRepository(repository1);
        verify(indexingService).indexRepository(repository2);
    }

    @Test
    public void testMissingRepository() {
        indexer.process("hierarchy", Lists.newArrayList(requestFor(REPO1_ID), requestFor(-1), requestFor(REPO2_ID)));

        verify(indexingService).indexRepository(repository1);
        verify(indexingService).indexRepository(repository2);
    }

    private HierarchyIndexingRequest requestFor(int repoId) {
        return new HierarchyIndexingRequest(repoId, "hierarchy");
    }
}
