package cz.moneta.test.dsl.payment_engine_mq;

import cz.moneta.test.dsl.Harness;
import cz.moneta.test.harness.constants.HarnessConfigConstants;
import cz.moneta.test.harness.endpoints.payment_engine.PaeMqEndpoint;
import cz.moneta.test.harness.support.auth.AuthSupport;
import cz.moneta.test.harness.support.auth.Credentials;
import cz.moneta.test.harness.support.rest.RawRestRequest;

import java.util.Base64;

public class PaeMqBuilder {
    private final Harness harness;

    public PaeMqBuilder(Harness harness) {
        this.harness = harness;
    }

    public RawRestRequest.Request prepareRequest(MessagingType messagingType) {
        PaeMqEndpoint endpoint = harness.getEndpoint(PaeMqEndpoint.class);
        String environment = harness.getConfig(HarnessConfigConstants.ENVIRONMENT_TYPE);
        String qmgr = resolveQueueManager(environment);
        String path = preparePath(messagingType, qmgr, environment);
        RawRestRequest.Request request = RawRestRequest.jsonBuilder(endpoint)
                .withPath(path)
                .withHeader("Authorization", getTokenFromCredentials());
        return addDefaultHeaders(request, qmgr);
    }

    private RawRestRequest.Request addDefaultHeaders(RawRestRequest.Request request, String qmgr) {
        return request
                .withHeader("Content-Type", "text/plain")
                .withHeader("ibm-mq-rest-csrf-token", "blank")
                .withHeader("ibm-mq-md-persistence", "persistent")
                .withHeader("ibm-mq-md-replyto", "REPLYQ")
                .withHeader("ibm-mq-md-replytoqmgr", qmgr);
    }

    private String getTokenFromCredentials() {
        Credentials cred = AuthSupport.getCredentials("pae-mq", harness);
        return "Basic " + Base64.getEncoder().encodeToString((cred.getUsername() + ":" + cred.getPassword()).getBytes());
    }

    private String preparePath(MessagingType messagingType, String qmgr, String environment) {
        String envPae = environment.equals("tst1") ? "TST" : "UAT";
        return String.format("qmgr/%s/queue/SAA.PAYHUB.%s.IN.%s/message", qmgr, messagingType.getValue(), envPae);
    }

    private String resolveQueueManager(String environment) {
        return environment.equals("tst1") ? "MSWIFTT" : "MSWIFTU";
    }

}