package cpm.com.gskmtorange.utils;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TLSSocketFactory extends SSLSocketFactory {
    private final SSLSocketFactory delegate;

    public TLSSocketFactory() {
        this.delegate = (SSLSocketFactory) SSLSocketFactory.getDefault();
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return delegate.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return delegate.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
        return enableModernTLS(delegate.createSocket(s, host, port, autoClose));
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException {
        return enableModernTLS(delegate.createSocket(host, port));
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
        return enableModernTLS(delegate.createSocket(host, port, localHost, localPort));
    }

    @Override
    public Socket createSocket(InetAddress host, int port) throws IOException {
        return enableModernTLS(delegate.createSocket(host, port));
    }

    @Override
    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
        return enableModernTLS(delegate.createSocket(address, port, localAddress, localPort));
    }

    private Socket enableModernTLS(Socket socket) {
        if (socket instanceof SSLSocket) {
            SSLSocket sslSocket = (SSLSocket) socket;

            // Supported protocols on this device
            String[] supported = sslSocket.getSupportedProtocols();

            // Collect TLSv1.2 and TLSv1.3 if available
            List<String> enabled = new ArrayList<>();
            for (String proto : supported) {
                if ("TLSv1.2".equals(proto) || "TLSv1.3".equals(proto)) {
                    enabled.add(proto);
                }
            }

            if (!enabled.isEmpty()) {
                sslSocket.setEnabledProtocols(enabled.toArray(new String[0]));
            }

            // Debug log
            System.out.println("Enabled protocols: " + Arrays.toString(sslSocket.getEnabledProtocols()));
        }
        return socket;
    }
}
