package com.foxx.androidcast.remoteaccess;

import org.json.JSONObject;
import org.junit.Test;

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

public class WireGuardConfigBuilderTest {

    @Test
    public void buildsConfigFromCredentials() throws Exception {
        JSONObject creds = new JSONObject();
        creds.put("interface_private_key", "aPrivKey=");
        creds.put("interface_address", "172.200.2.10/32");
        creds.put("peer_public_key", "aPubKey=");
        creds.put("peer_endpoint", "ra.apps.f0xx.org:45340");
        creds.put("peer_allowed_ips", "172.200.2.1/32");
        String cfg = WireGuardConfigBuilder.fromConnectCredentials(
                creds,
                RemoteAccessVpnRouting.RouteScope.HUB_ONLY,
                RemoteAccessVpnRouting.AppScope.ALL_APPS,
                "com.foxx.androidcast");
        assertTrue(cfg.contains("[Interface]"));
        assertTrue(cfg.contains("PrivateKey = aPrivKey="));
        assertTrue(cfg.contains("PublicKey = aPubKey="));
        assertTrue(cfg.contains("Endpoint = ra.apps.f0xx.org:45340"));
        assertTrue(cfg.contains("AllowedIPs = 172.200.2.1/32"));
        assertFalse(cfg.contains("IncludedApplications"));
    }

    @Test
    public void fullTunnelOverridesBeAllowedIps() throws Exception {
        JSONObject creds = new JSONObject();
        creds.put("interface_private_key", "aPrivKey=");
        creds.put("interface_address", "172.200.2.10/32");
        creds.put("peer_public_key", "aPubKey=");
        creds.put("peer_allowed_ips", "172.200.2.1/32");
        String cfg = WireGuardConfigBuilder.fromConnectCredentials(
                creds,
                RemoteAccessVpnRouting.RouteScope.FULL_TUNNEL,
                RemoteAccessVpnRouting.AppScope.ALL_APPS,
                null);
        assertTrue(cfg.contains("AllowedIPs = 0.0.0.0/0, ::/0"));
    }

    @Test
    public void appOnlyAddsIncludedApplications() throws Exception {
        JSONObject creds = new JSONObject();
        creds.put("interface_private_key", "aPrivKey=");
        creds.put("interface_address", "172.200.2.10/32");
        creds.put("peer_public_key", "aPubKey=");
        String cfg = WireGuardConfigBuilder.fromConnectCredentials(
                creds,
                RemoteAccessVpnRouting.RouteScope.HUB_ONLY,
                RemoteAccessVpnRouting.AppScope.THIS_APP_ONLY,
                "com.foxx.androidcast");
        assertTrue(cfg.contains("IncludedApplications = com.foxx.androidcast"));
    }

    @Test
    public void emptyWhenMissingKeys() throws Exception {
        JSONObject creds = new JSONObject();
        creds.put("interface_address", "172.200.2.10/32");
        assertTrue(WireGuardConfigBuilder.fromConnectCredentials(
                creds,
                RemoteAccessVpnRouting.RouteScope.HUB_ONLY,
                RemoteAccessVpnRouting.AppScope.ALL_APPS,
                null).isEmpty());
    }
}
