package com.foxx.androidcast.remoteaccess;

import android.util.Log;

import org.json.JSONObject;

/** Build wireguard-quick style config from BE connect credentials. */
public final class WireGuardConfigBuilder {
    private static final String TAG = "WireGuardCfg";

    private WireGuardConfigBuilder() {}

    public static String fromConnectCredentials(JSONObject credentials) {
        if (credentials == null) {
            return "";
        }
        String priv = credentials.optString("interface_private_key", "");
        String addr = credentials.optString("interface_address", "10.66.66.2/32");
        String peerPub = credentials.optString("peer_public_key", "");
        String endpoint = credentials.optString("peer_endpoint", "");
        String allowed = credentials.optString("peer_allowed_ips", "0.0.0.0/0");
        if (priv.isEmpty() || peerPub.isEmpty()) {
            Log.w(TAG, "missing wg keys in credentials");
            return "";
        }
        StringBuilder sb = new StringBuilder();
        sb.append("[Interface]\n");
        sb.append("PrivateKey = ").append(priv).append('\n');
        sb.append("Address = ").append(addr).append('\n');
        sb.append('\n');
        sb.append("[Peer]\n");
        sb.append("PublicKey = ").append(peerPub).append('\n');
        if (!endpoint.isEmpty()) {
            sb.append("Endpoint = ").append(endpoint).append('\n');
        }
        sb.append("AllowedIPs = ").append(allowed).append('\n');
        sb.append("PersistentKeepalive = 25\n");
        return sb.toString();
    }
}
