package com.foxx.androidcast.remoteaccess;

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

import com.wireguard.config.Config;

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

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;

/** Ensures BE credential → wg-quick text parses with wireguard-android Config. */
public class WireGuardConfigParseTest {

    @Test
    public void builderOutput_parsesWithWireGuardConfig() throws Exception {
        JSONObject creds = new JSONObject();
        creds.put("interface_private_key", "YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=");
        creds.put("interface_address", "172.200.2.10/32");
        creds.put("peer_public_key", "YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=");
        creds.put("peer_endpoint", "ra.apps.f0xx.org:45340");
        creds.put("peer_allowed_ips", "172.200.2.1/32");

        String quick = WireGuardConfigBuilder.fromConnectCredentials(
                creds,
                RemoteAccessVpnRouting.RouteScope.HUB_ONLY,
                RemoteAccessVpnRouting.AppScope.ALL_APPS,
                null);
        assertFalse(quick.isEmpty());

        try (ByteArrayInputStream in = new ByteArrayInputStream(quick.getBytes(StandardCharsets.UTF_8))) {
            Config config = Config.parse(in);
            assertEquals("172.200.2.10/32", config.getInterface().getAddresses().iterator().next().toString());
        }
    }

    @Test
    public void appOnly_includedApplicationsParse() throws Exception {
        JSONObject creds = new JSONObject();
        creds.put("interface_private_key", "YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=");
        creds.put("interface_address", "172.200.2.10/32");
        creds.put("peer_public_key", "YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=");

        String quick = WireGuardConfigBuilder.fromConnectCredentials(
                creds,
                RemoteAccessVpnRouting.RouteScope.HUB_ONLY,
                RemoteAccessVpnRouting.AppScope.THIS_APP_ONLY,
                "com.foxx.androidcast");
        assertFalse(quick.isEmpty());

        try (ByteArrayInputStream in = new ByteArrayInputStream(quick.getBytes(StandardCharsets.UTF_8))) {
            Config config = Config.parse(in);
            assertEquals(1, config.getInterface().getIncludedApplications().size());
            assertEquals("com.foxx.androidcast", config.getInterface().getIncludedApplications().iterator().next());
        }
    }
}
