namespace Neta.Tray;

public static class ShutdownCommand
{
    public static void Run()
    {
        Run(AppContext.BaseDirectory);
    }

    public static void Run(string baseDirectory)
    {
        var backendExePath = Path.Combine(baseDirectory, "backend.exe");
        var processManager = new BackendProcessManager();
        var runtime = RuntimeInfoStore.LoadFromInstalledConfig(baseDirectory);
        if (runtime is not null)
        {
            using var httpClient = new HttpClient();
            var statusClient = new StatusClient(httpClient);
            try
            {
                statusClient.StopAsync(runtime, CancellationToken.None).GetAwaiter().GetResult();
            }
            catch
            {
            }

            processManager.WaitForExit(runtime.Pid, TimeSpan.FromSeconds(10));
            if (processManager.IsBackendProcessAlive(runtime.Pid))
            {
                processManager.KillProcess(runtime.Pid);
            }
        }

        processManager.KillInstalledBackendProcesses(backendExePath);
    }

    public static void OpenExistingInstance()
    {
    }
}
