package it.com.atlassian.stash.hosting;

import com.atlassian.bitbucket.permission.Permission;
import com.atlassian.stash.hosting.HttpScmTransport;
import com.atlassian.bitbucket.test.DefaultFuncTestData;
import com.atlassian.bitbucket.test.GitTestHelper;
import com.atlassian.bitbucket.test.ProcessFailedException;
import com.atlassian.bitbucket.test.ProcessTestHelper;
import org.junit.Before;
import org.junit.Test;

import java.io.Closeable;

import static it.com.atlassian.stash.hosting.HostingTestHelper.enableHook;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

public class BundledHooksHostingTest extends BaseHostingTest {

    private static final String TEST_USER = "bundled-hooks-tester";
    private static final String TEST_PROJECT = DefaultFuncTestData.getProject1();
    private static final String TEST_REPO = "bundled-hooks";

    private HttpScmTransport transport;

    @Before
    public void onSetup() throws Exception {
        transport = new HttpScmTransport(TEST_USER, TEST_USER);
        testContext.user(TEST_USER);
        testContext.repository(TEST_PROJECT, TEST_REPO);
        testContext.projectPermission(TEST_PROJECT, TEST_USER, Permission.PROJECT_WRITE);
        transport.clone(tempFolder.getRoot(), TEST_PROJECT, TEST_REPO);
        addCommit("foo", "adding a file");
        ProcessTestHelper.execute(tempFolder.getRoot(), GitTestHelper.getGitPath(), "branch", "first");
        addCommit("bar", "updated a file");
        transport.pushAllRefs(tempFolder.getRoot(), TEST_PROJECT, TEST_REPO);
    }

    private void addCommit(String fileContent, String message) throws Exception {
        HostingTestHelper.createAndAdd(tempFolder.getRoot(), "fist.txt", fileContent);
        HostingTestHelper.commit(tempFolder.getRoot(), message);
    }

    @Test
    public void testForcePushRejection() throws Exception {
        try (Closeable ignored = enableHook(TEST_PROJECT, TEST_REPO, "com.atlassian.bitbucket.server.bitbucket-bundled-hooks:force-push-hook")) {
            ProcessTestHelper.execute(tempFolder.getRoot(), GitTestHelper.getGitPath(), "reset", "--hard", "first");
            try {
                transport.pushAllRefs(tempFolder.getRoot(), TEST_PROJECT, TEST_REPO, "-f");
                fail("Push should not succeed");
            } catch (ProcessFailedException e) {
                assertThat(e.getMessage().toLowerCase(), containsString("force-push"));
            }
        }
    }

}
