using CodeRemoteManager.SetupApp;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace CodeRemoteManager.SetupApp.Tests;

[TestClass]
public sealed class BackendConfigurationValidatorTests
{
    [TestMethod]
    public async Task UsesActualBackendLoaderForCandidateValidation()
    {
        var directory = Directory.CreateTempSubdirectory("crm-backend-validator-");
        try
        {
            var configPath = Path.Combine(directory.FullName, "candidate.json");
            var candidate = ConfigurationMigration.BuildCandidate(
                null,
                new SetupConfigurationInput(
                    "codex.cmd",
                    "https://device.example.ts.net",
                    "C:\\Projects\\Candidate"),
                new SetupConfigurationDefaults("private-data", "desktop-home"));
            await File.WriteAllTextAsync(configPath, candidate.ToJsonString());
            var validator = new BackendConfigurationValidator(
                "node.exe",
                RepositoryFile("apps", "backend", "src", "config-validator-cli.js"));

            await validator.ValidateAsync(configPath);

            candidate["schemaVersion"] = 2;
            await File.WriteAllTextAsync(configPath, candidate.ToJsonString());
            var error = await Assert.ThrowsExceptionAsync<ConfigurationMigrationException>(() =>
                validator.ValidateAsync(configPath));
            Assert.AreEqual("configuration_invalid", error.Message);
        }
        finally
        {
            directory.Delete(recursive: true);
        }
    }

    private static string RepositoryFile(params string[] segments)
    {
        var directory = new DirectoryInfo(AppContext.BaseDirectory);
        while (directory is not null && !Directory.Exists(Path.Combine(directory.FullName, "apps")))
            directory = directory.Parent;
        Assert.IsNotNull(directory);
        return Path.Combine([directory.FullName, .. segments]);
    }
}
