use std::{
    path::{Path, PathBuf},
    process::Command,
};

use tauri::{AppHandle, Manager};

pub fn current_tunnel_strategy() -> &'static str {
    if cfg!(target_os = "windows") {
        "embedded-wireguard-windows-x64"
    } else if cfg!(target_os = "macos") {
        "embedded-wireguard-macos-arm"
    } else {
        "unsupported"
    }
}

pub fn connect(app: &AppHandle, profile_path: &Path) -> Result<(), String> {
    let backend = bundled_backend(app)?;
    let status = Command::new(backend)
        .arg("connect")
        .arg("--profile")
        .arg(profile_path)
        .status()
        .map_err(|err| format!("Unable to start embedded tunnel backend: {}", err))?;

    if !status.success() {
        return Err(format!("Embedded tunnel backend connect failed with status {}", status));
    }

    Ok(())
}

pub fn disconnect(app: &AppHandle, profile_path: &Path) -> Result<(), String> {
    let backend = bundled_backend(app)?;
    let status = Command::new(backend)
        .arg("disconnect")
        .arg("--profile")
        .arg(profile_path)
        .status()
        .map_err(|err| format!("Unable to stop embedded tunnel backend: {}", err))?;

    if !status.success() {
        return Err(format!("Embedded tunnel backend disconnect failed with status {}", status));
    }

    Ok(())
}

fn bundled_backend(app: &AppHandle) -> Result<PathBuf, String> {
    let resource_dir = app
        .path()
        .resource_dir()
        .map_err(|err| format!("Unable to resolve resource dir: {}", err))?;

    let relative = if cfg!(target_os = "windows") {
        PathBuf::from("bundled/windows-x64/nexavpn-tunnel-helper.exe")
    } else if cfg!(target_os = "macos") {
        PathBuf::from("bundled/macos-arm64/nexavpn-tunnel-helper")
    } else {
        return Err("This NexaVPN client build supports embedded tunnel backends only for Windows x64 and macOS ARM".into());
    };

    let path = resource_dir.join(relative);
    if !path.exists() {
        return Err("Embedded NexaVPN tunnel backend is not bundled in this build yet.".into());
    }

    Ok(path)
}
