package nl.htm.ovpay.abt;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class APIHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(APIHelper.class);
    private static final String PRODUCT_DETAILS_URI = "https://services.<ENV>.api.htm.nl/abt/abtproducts/1.0/products/<PRODUCTID>";


    public static String envToUriPart(String environment) {
        return switch (environment) {
            case "DEV" -> "dev";
            case "ACC" -> "acc";
            case "PRD" -> "";
            default -> throw new IllegalArgumentException("Invalid environment: " + environment);
        };
    }

    public static String getProductDetails(String environment, String productId, String wso2BearerToken) throws Exception {
        var envUriPart = envToUriPart(environment);
        var getProductDetailsUri = PRODUCT_DETAILS_URI.replace("<ENV>", envUriPart).replace("<PRODUCTID>", productId);

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, DummyX509TrustManager.getDummyArray(), new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        URL url = new URL(getProductDetailsUri);
        URLConnection con = url.openConnection();
        HttpURLConnection http = (HttpURLConnection)con;
        http.setRequestMethod("GET");
        http.setDoOutput(false);
        http.setRequestProperty("Authorization", "Bearer " + wso2BearerToken);
        http.connect();

        try(InputStream is = http.getInputStream()) {
            return new String(is.readAllBytes(), StandardCharsets.UTF_8);
        }
    }

    public static void putProductDetails(String environment, String productId, String jsonBody, String wso2BearerToken) throws Exception {
        var envUriPart = envToUriPart(environment);
        var putProductDetailsUri = PRODUCT_DETAILS_URI.replace("<ENV>", envUriPart).replace("<PRODUCTID>", productId);

        LOGGER.info("PUT product details to URI: {}", putProductDetailsUri);

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, DummyX509TrustManager.getDummyArray(), new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        URL url = new URL(putProductDetailsUri);
        URLConnection con = url.openConnection();
        HttpURLConnection http = (HttpURLConnection)con;
        http.setRequestMethod("PUT");
        http.setDoOutput(true);
        http.setRequestProperty("Authorization", "Bearer " + wso2BearerToken);
        http.setRequestProperty("Content-Type", "application/json");

        byte[] out = jsonBody.getBytes(StandardCharsets.UTF_8);
        int length = out.length;
        http.setFixedLengthStreamingMode(length);
        http.connect();

        try(OutputStream os = http.getOutputStream()) {
            os.write(out);
        }

        try(InputStream is = http.getInputStream()) {
            LOGGER.info("Got response from PUT API: {}", new String(is.readAllBytes(), StandardCharsets.UTF_8));
        }
    }
}
