package dev.lions.user.manager.security;

import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.SecurityContext;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.lang.reflect.Field;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

/**
 * Tests unitaires pour DevSecurityContextProducer
 */
@ExtendWith(MockitoExtension.class)
class DevSecurityContextProducerTest {

    @Mock
    private ContainerRequestContext requestContext;

    @Mock
    private UriInfo uriInfo;

    @Mock
    private SecurityContext originalSecurityContext;

    private DevSecurityContextProducer producer;

    @BeforeEach
    void setUp() throws Exception {
        producer = new DevSecurityContextProducer();
        
        // Injecter les propriétés via reflection
        setField("profile", "dev");
        setField("oidcEnabled", false);
    }

    private void setField(String fieldName, Object value) throws Exception {
        Field field = DevSecurityContextProducer.class.getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(producer, value);
    }

    @Test
    void testFilter_DevMode() throws Exception {
        setField("profile", "dev");
        setField("oidcEnabled", true);

        when(requestContext.getUriInfo()).thenReturn(uriInfo);
        when(uriInfo.getPath()).thenReturn("/api/users");
        when(requestContext.getSecurityContext()).thenReturn(originalSecurityContext);

        producer.filter(requestContext);

        verify(requestContext, times(1)).setSecurityContext(any(SecurityContext.class));
    }

    @Test
    void testFilter_ProdMode() throws Exception {
        setField("profile", "prod");
        setField("oidcEnabled", true);

        // En mode prod, on n'a pas besoin de mocker getUriInfo car le code ne l'utilise pas
        producer.filter(requestContext);

        verify(requestContext, never()).setSecurityContext(any(SecurityContext.class));
    }

    @Test
    void testFilter_OidcDisabled() throws Exception {
        setField("profile", "prod");
        setField("oidcEnabled", false);

        when(requestContext.getUriInfo()).thenReturn(uriInfo);
        when(uriInfo.getPath()).thenReturn("/api/users");
        when(requestContext.getSecurityContext()).thenReturn(originalSecurityContext);

        producer.filter(requestContext);

        verify(requestContext, times(1)).setSecurityContext(any(SecurityContext.class));
    }
}

