package com.magistr.app.config.auth;

import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class ClientIpResolverTest {

    @Test
    void ignoresForwardedHeaderFromUntrustedClient() {
        ClientIpResolver resolver = new ClientIpResolver("10.42.0.0/16");
        MockHttpServletRequest request = request("203.0.113.7", "192.0.2.10");

        assertThat(resolver.resolve(request)).isEqualTo("203.0.113.7");
    }

    @Test
    void selectsFirstUntrustedAddressFromRightBehindTrustedProxyChain() {
        ClientIpResolver resolver = new ClientIpResolver("10.42.0.0/16, 172.16.0.0/12");
        MockHttpServletRequest request = request(
                "10.42.1.15",
                "192.0.2.99, 198.51.100.23, 172.18.0.4"
        );

        assertThat(resolver.resolve(request)).isEqualTo("198.51.100.23");
    }

    @Test
    void rejectsEntireForwardedHeaderWhenItContainsInvalidAddress() {
        ClientIpResolver resolver = new ClientIpResolver("10.42.0.0/16");
        MockHttpServletRequest request = request("10.42.1.15", "198.51.100.23, attacker.example");

        assertThat(resolver.resolve(request)).isEqualTo("10.42.1.15");
    }

    @Test
    void rejectsInvalidTrustedProxyConfigurationAtStartup() {
        assertThatThrownBy(() -> new ClientIpResolver("10.42.0.0/99"))
                .isInstanceOf(IllegalStateException.class)
                .hasMessageContaining("Некорректная маска");
    }

    private MockHttpServletRequest request(String remoteAddress, String forwardedFor) {
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.setRemoteAddr(remoteAddress);
        request.addHeader("X-Forwarded-For", forwardedFor);
        return request;
    }
}
