import { addPluginListener, invoke } from "@tauri-apps/api/core";

export interface TunnelConfig {
  address: string;
  prefix: number;
  dns: string;
  mtu: number;
  killswitchEnabled: boolean;
  excludedApps: string[];
  excludedDomains: string[];
  allowedApps?: string[];
  /** Bearer-токен для прокси-инстансов с `--require-auth`; `undefined` — не проверяется. */
  authToken?: string;
}

export interface TrafficStatsResponse {
  rxBytes: number;
  txBytes: number;
  rxPackets: number;
  txPackets: number;
}

export interface AppInfo {
  appName: string;
  packageName: string;
}

export async function startVpn(
  config: TunnelConfig,
  ip: string,
  port: number,
  sni: string,
) {
  return await invoke("plugin:vpn|start_vpn", { config, ip, port, sni });
}

export async function stopVpn() {
  return await invoke("plugin:vpn|stop_vpn");
}

export async function checkActualVpnStatus(): Promise<"connected" | "idle"> {
  try {
    const result = await invoke<{ status: string }>(
      "plugin:vpn|check_actual_vpn_status",
    );
    return result.status as "connected" | "idle";
  } catch (e) {
    return "idle";
  }
}

export const setupVpnStatusListener = async (callback: (p: any) => void) => {
  return await addPluginListener("vpn", "status-change", (payload) => {
    callback(payload);
  });
};

export const setupTrafficStatsListener = async (
  callback: (stats: TrafficStatsResponse) => void,
) => {
  return await addPluginListener("vpn", "traffic-stats", (payload) => {
    callback(payload as TrafficStatsResponse);
  });
};

export async function getInstalledApps(): Promise<AppInfo[]> {
  return await invoke<AppInfo[]>("plugin:vpn|get_installed_apps");
}

// НОВАЯ ФУНКЦИЯ ДЛЯ ЗАПУСКА ТЕЛЕГИ
export async function launchApp(packageName: string): Promise<void> {
  return await invoke("plugin:vpn|launch_app", { packageName });
}
