package com.atlassian.bitbucket.internal.branch.automerge;

import com.atlassian.bitbucket.event.repository.RepositoryDeletedEvent;
import com.atlassian.bitbucket.permission.PermissionValidationService;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.server.ApplicationPropertiesService;
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

public class DefaultAutoMergeConfigTest {

    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule();

    @Mock
    private ApplicationPropertiesService applicationProperties;
    private DefaultAutoMergeConfig config;
    @Mock
    private PluginSettingsFactory pluginSettingsFactory;
    @Mock
    private PermissionValidationService permissionValidationService;
    @Mock
    private Repository repository;
    @Mock
    private PluginSettings settings;

    @Before
    public void setup() {
        when(repository.getId()).thenReturn(1);
        when(repository.getSlug()).thenReturn("test");

        when(pluginSettingsFactory.createSettingsForKey(DefaultAutoMergeConfig.SETTINGS_KEY)).thenReturn(settings);

        config = new DefaultAutoMergeConfig(applicationProperties, permissionValidationService, pluginSettingsFactory);
    }

    @Test
    public void testGetLimit() {
        when(applicationProperties.getPluginProperty(eq(DefaultAutoMergeConfig.PROP_LIMIT), anyInt())).thenReturn(34);
        assertEquals(34, config.getLimit());
    }

    @Test
    public void testGetTimeout() {
        when(applicationProperties.getPluginProperty(eq(DefaultAutoMergeConfig.PROP_TIMEOUT), anyLong()))
                .thenReturn(300L);

        assertEquals(300L, config.getTimeout());
    }

    @Test
    public void testIsEnabled() {
        when(settings.get("enabled.1")).thenReturn("true");
        assertTrue(config.isEnabled(repository));
    }

    @Test
    public void testIsEnabledHandlesNull() {
        when(settings.get("enabled.1")).thenReturn(null);
        assertFalse(config.isEnabled(repository));
    }

    @Test
    public void testOnRepositoryDeleted() {
        config.onRepositoryDeleted(new RepositoryDeletedEvent(this, repository));
        verify(settings).remove("enabled.1");
    }

    @Test
    public void testSetEnabled() {
        config.setEnabled(repository, true);
        verify(settings).put("enabled.1", "true");
    }
}
