/**
 * Copyright © 2012-2025 by Data Virtuality GmbH
 */
package org.teiid.transport;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.teiid.jdbc.FipsManager;
import org.teiid.jdbc.JDBCPlugin;
import org.teiid.net.TeiidURL;
import org.teiid.net.socket.SocketUtil;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.security.GeneralSecurityException;
import java.util.Properties;

import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;

/**
 *
 *
 * @author Roman Pedchenko
 * @date 2025.10.15
 */
public class TestFipsConfiguration {
    @BeforeEach
    void setUp() throws Exception {
        Properties props = new Properties();
        props.setProperty(TeiidURL.CONNECTION.FIPS, "enabled");
        FipsManager.initializeFipsMode(props);
    }

    @AfterEach
    void tearDown() {
        FipsManager.removeFipsProvider();
    }

    @Test
    public void testError() {
        SSLConfiguration config = new SSLConfiguration();
        config.setMode("enabled");
        config.setFips("enabled");
        config.setKeystoreFilename("keystore.jks");
        assertThatThrownBy(config::getServerSSLEngine)
                .isInstanceOf(GeneralSecurityException.class)
                .hasMessage(JDBCPlugin.Util.getString("fips_strict_requires_bcfks"));
    }

    @Test
    public void testSuccess() throws Exception {
        SSLConfiguration config = new SSLConfiguration();
        config.setMode("enabled");
        config.setFips("enabled");
        config.setKeystoreFilename("keystore.jks");
        config.setKeystoreType("bcfks");

        try (MockedStatic<SocketUtil> su = mockStatic(SocketUtil.class)) {
            SSLContext ctx = mock(SSLContext.class);
            SSLEngine en = mock(SSLEngine.class);
            when(ctx.createSSLEngine()).thenReturn(en);
            su.when(() -> SocketUtil.getSSLContext(
                            nullable(String.class),
                            nullable(String.class),
                            nullable(String.class),
                            nullable(String.class),
                            nullable(String.class),
                            nullable(String.class),
                            nullable(String.class),
                            nullable(String.class),
                            nullable(String.class)
                    ))
                    .thenReturn(ctx);

            config.getServerSSLEngine();
        }
    }
}
