package dev.lions.unionflow.server.client;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import io.quarkus.security.identity.SecurityIdentity;
import jakarta.enterprise.inject.Instance;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import java.lang.reflect.Field;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

/**
 * Test SANS @QuarkusTest pour couvrir la branche {@code identity == null}
 * dans {@link OidcTokenPropagationHeadersFactory#update} (L49).
 *
 * <p>En contexte CDI, {@code securityIdentity.get()} ne retourne jamais null.
 * On instancie {@link OidcTokenPropagationHeadersFactory} directement et injecte
 * un {@link Instance} dont {@code get()} retourne null.
 */
class OidcTokenPropagationHeadersFactoryNullIdentityTest {

    @SuppressWarnings("unchecked")
    @Test
    @DisplayName("update : securityIdentity.get() retourne null → warn + résultat vide (branche identity==null L49)")
    void update_identityGetReturnsNull_returnsEmptyResult() throws Exception {
        OidcTokenPropagationHeadersFactory factory = new OidcTokenPropagationHeadersFactory();

        // Crée un mock Instance<SecurityIdentity> dont get() retourne null
        Instance<SecurityIdentity> mockInstance = mock(Instance.class);
        when(mockInstance.get()).thenReturn(null);

        Field siField = OidcTokenPropagationHeadersFactory.class.getDeclaredField("securityIdentity");
        siField.setAccessible(true);
        siField.set(factory, mockInstance);

        MultivaluedMap<String, String> incoming = new MultivaluedHashMap<>();
        // Pas d'Authorization → stratégie 1 sautée → stratégie 2 : identity == null → warn
        MultivaluedMap<String, String> outgoing = new MultivaluedHashMap<>();

        MultivaluedMap<String, String> result = factory.update(incoming, outgoing);

        assertThat(result).isNotNull();
        assertThat(result.containsKey("Authorization")).isFalse();
    }
}
