using System.Diagnostics;

namespace CodeRemoteManager.SetupApp;

public sealed class BackendConfigurationValidator(
    string nodeExecutable,
    string validatorScript)
{
    public async Task ValidateAsync(
        string configPath,
        CancellationToken cancellationToken = default)
    {
        var startInfo = new ProcessStartInfo(nodeExecutable)
        {
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };
        startInfo.ArgumentList.Add(validatorScript);
        startInfo.Environment["CODE_REMOTE_MANAGER_CONFIG_PATH"] = configPath;

        try
        {
            using var process = Process.Start(startInfo)
                ?? throw new InvalidOperationException();
            var discardOutput = process.StandardOutput.ReadToEndAsync(cancellationToken);
            var discardError = process.StandardError.ReadToEndAsync(cancellationToken);
            await process.WaitForExitAsync(cancellationToken);
            await Task.WhenAll(discardOutput, discardError);
            if (process.ExitCode != 0)
                throw new ConfigurationMigrationException("configuration_invalid");
        }
        catch (ConfigurationMigrationException)
        {
            throw;
        }
        catch
        {
            throw new ConfigurationMigrationException("configuration_validation_failed");
        }
    }
}
