package lc.esp.job;

import lc.mecha.http.client.HttpClientRig;
import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import lc.mecha.security.CertUtil;
import lc.mecha.security.CertificateKeyStore;
import lc.mecha.security.KeyUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.operator.OperatorCreationException;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.UUID;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class TestESPControlPlane {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(TestESPControlPlane.class);

    @Test
    public void create() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
            IOException, OperatorCreationException, KeyManagementException, CloneNotSupportedException {
        final var ks = KeyStore.getInstance(KeyStore.getDefaultType());
        final var pw = UUID.randomUUID().toString();
        ks.load(null, null);

        var kp = KeyUtil.generateRSAKeyPair(1024);
        var cert = CertUtil.selfSign(kp, "cn=localhost");
        var keyPass = pw.toCharArray();
        var chain = new X509Certificate[]{cert};
        var cks = new CertificateKeyStore(ks, pw);

        // Note that keypass is mandatory
        ks.setKeyEntry(ESPControlPlane.SSL_CERTIFICATE_ALIAS, kp.getPrivate(), keyPass, chain);
        logger.info("Generated key & cert. [key: {}] [cert: {}]", kp, cert);

        ESPControlPlane svc = new ESPControlPlane(cks);
        svc.setPort(9123);
        svc.start();

        HttpClientRig rig = new HttpClientRig(true, cks);
        CloseableHttpClient client = rig.getClient();
        HttpGet httpGet = new HttpGet("https://localhost:9123");

        try (CloseableHttpResponse response1 = client.execute(httpGet)) {
            assertEquals("HTTP/1.1 404 Not Found", response1.getStatusLine().toString());
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            EntityUtils.consume(entity1);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
