package org.whoneedhelp.mobile;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public final class TrustedOriginTest {
    @Test
    public void acceptsSameHttpsOriginAndDefaultPort() {
        TrustedOrigin origin = TrustedOrigin.parse("https://help.example", false);

        assertTrue(origin.matches("https://help.example/requests/123"));
        assertTrue(origin.matches("https://help.example:443/profile"));
        assertFalse(origin.matches("https://help.example.evil.test/"));
        assertFalse(origin.matches("http://help.example/"));
        assertFalse(origin.matches("https://help.example:444/"));
        assertEquals("https://help.example", origin.originRule());
    }

    @Test
    public void debugBuildCanUseEmulatorLoopback() {
        TrustedOrigin origin = TrustedOrigin.parse("http://10.0.2.2:4010", true);

        assertTrue(origin.matches("http://10.0.2.2:4010/requests"));
        assertTrue(origin.matchesOrigin("http://10.0.2.2:4010/"));
        assertFalse(origin.matchesOrigin("http://10.0.2.2:4010/requests"));
        assertEquals("http://10.0.2.2:4010", origin.originRule());
    }

    @Test
    public void releaseRejectsHttpAndCredentialedOrigins() {
        assertThrows(
            IllegalArgumentException.class,
            () -> TrustedOrigin.parse("http://help.example", false)
        );
        assertThrows(
            IllegalArgumentException.class,
            () -> TrustedOrigin.parse("https://user@help.example", false)
        );
        assertThrows(
            IllegalArgumentException.class,
            () -> TrustedOrigin.parse("https://help.example?redirect=evil", false)
        );
        assertThrows(
            IllegalArgumentException.class,
            () -> TrustedOrigin.parse("https://help.example/app", false)
        );
    }
}
