package cz.moneta.test.dsl.util.task.wso2.authorization;

import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.wso2.Wso2GatewayEndpoint;
import cz.moneta.test.harness.support.rest.RawRestRequest;

import java.util.Base64;

public class AuthorizationTasks {

    private final StoreAccessor harness;

    public AuthorizationTasks(StoreAccessor harness) {
        this.harness = harness;
    }

    public String ufoToken() {
        return getToken("UFO");
    }

    public String getToken(String sourceAppName) {
        return getBearerToken("CID_" + sourceAppName, "CS_" + sourceAppName);
    }

    private String getBearerToken(String key, String secret) {
        Wso2GatewayEndpoint endpoint = harness.getEndpoint(Wso2GatewayEndpoint.class);
        String username = endpoint.getClientSecret(key);
        String password = endpoint.getClientSecret(secret);
        String basicToken = Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
        return "Bearer " + RawRestRequest.customJsonBuilder(endpoint, "application/x-www-form-urlencoded")
                .withPath("/token")
                .withHeader("Authorization", "Basic " + basicToken)
                .withPayload("grant_type=client_credentials")
                .post()
                .extract("access_token")
                .asText();
    }

    public String encodeCredentialsToWsoAuth(String consumerKey, String consumerSecret) {
        return Base64.getEncoder().encodeToString((consumerKey + ":" + consumerSecret).getBytes());
    }
}