package com.foxx.androidcast.remoteaccess;

import android.content.Context;

import com.foxx.androidcast.AppPreferences;

/** Developer VPN routing: which destinations and which apps use the tunnel (WireGuard). */
public final class RemoteAccessVpnRouting {
    public static final String DEFAULT_HUB_ALLOWED_IPS = "172.200.2.1/32";
    public static final String FULL_TUNNEL_ALLOWED_IPS = "0.0.0.0/0, ::/0";

    public enum RouteScope {
        /** Split tunnel — hub WG address only (production default). */
        HUB_ONLY,
        /** Route all IPv4/IPv6 through the tunnel when it is up. */
        FULL_TUNNEL;

        public static RouteScope fromStored(String raw) {
            if (raw == null || raw.isEmpty()) {
                return HUB_ONLY;
            }
            try {
                return valueOf(raw.trim().toUpperCase());
            } catch (IllegalArgumentException e) {
                return HUB_ONLY;
            }
        }
    }

    public enum AppScope {
        /** Any app whose traffic matches AllowedIPs may use the VPN routes. */
        ALL_APPS,
        /** Only this app's traffic uses the VPN routes (VpnService / IncludedApplications). */
        THIS_APP_ONLY;

        public static AppScope fromStored(String raw) {
            if (raw == null || raw.isEmpty()) {
                return ALL_APPS;
            }
            try {
                return valueOf(raw.trim().toUpperCase());
            } catch (IllegalArgumentException e) {
                return ALL_APPS;
            }
        }
    }

    private RemoteAccessVpnRouting() {}

    public static RouteScope routeScope(Context context) {
        return AppPreferences.getDevRemoteAccessVpnRouteScope(context);
    }

    public static AppScope appScope(Context context) {
        return AppPreferences.getDevRemoteAccessVpnAppScope(context);
    }

    public static String resolveAllowedIps(RouteScope routeScope, String bePeerAllowedIps) {
        if (routeScope == RouteScope.FULL_TUNNEL) {
            return FULL_TUNNEL_ALLOWED_IPS;
        }
        String hub = bePeerAllowedIps != null ? bePeerAllowedIps.trim() : "";
        return hub.isEmpty() ? DEFAULT_HUB_ALLOWED_IPS : hub;
    }

    public static void appendInterfaceExtras(
            StringBuilder sb,
            AppScope appScope,
            String packageName) {
        if (appScope == AppScope.THIS_APP_ONLY
                && packageName != null
                && !packageName.isEmpty()) {
            sb.append("IncludedApplications = ").append(packageName).append('\n');
        }
    }

    public static String routeScopeLabel(RouteScope scope) {
        return scope != null ? scope.name().toLowerCase() : RouteScope.HUB_ONLY.name().toLowerCase();
    }

    public static String appScopeLabel(AppScope scope) {
        return scope != null ? scope.name().toLowerCase() : AppScope.ALL_APPS.name().toLowerCase();
    }
}
