package com.atlassian.bitbucket.test;

import com.google.common.collect.ImmutableMap;
import com.jayway.restassured.RestAssured;

import static javax.ws.rs.core.Response.Status.CREATED;
import static javax.ws.rs.core.Response.Status.NO_CONTENT;
import static org.hamcrest.Matchers.equalTo;

/**
 * Test utilities for the creation & deletion of Branches via the REST interface.
 */
public final class BranchTestHelper {

    public static void createBranch(String projectKey, String repoSlug, String branchName, String branchFrom) {
        RestAssured
            .given()
                .auth().preemptive().basic(DefaultFuncTestData.getAdminUser(), DefaultFuncTestData.getAdminPassword())
                .contentType("application/json")
                .body(ImmutableMap.of("name", branchName, "startPoint", branchFrom))
            .expect().statusCode(CREATED.getStatusCode())
                .log().ifError()
                .body("displayId", equalTo(branchName))
                .body("latestCommit", equalTo(branchFrom))
                .body("isDefault", equalTo(false))
            .when().post(getBranchURL(projectKey, repoSlug));
    }

    public static void deleteBranch(String projectKey, String repoSlug, String branchName) {
        RestAssured
            .given()
                .auth().preemptive().basic(DefaultFuncTestData.getAdminUser(), DefaultFuncTestData.getAdminPassword())
                .contentType("application/json")
                .body(ImmutableMap.of("name", branchName, "dryRun", false))
            .expect().statusCode(NO_CONTENT.getStatusCode())
                .log().ifError()
            .when().delete(getBranchURL(projectKey, repoSlug));
    }

    private static String getBranchURL(String projectKey, String repoSlug) {
        return DefaultFuncTestData.getRepositoryRestURL("branch-utils", "latest", projectKey, repoSlug) + "/branches";
    }

}
