using NexusInstaller.Services;
using Xunit;

namespace NexusInstaller.Tests;

public sealed class NexusIdentityDataPathsTests
{
    [Fact]
    public void ResolveDatabasePath_UsesDataIdentityUnderInstallRoot()
    {
        var root = Path.Combine(Path.GetTempPath(), $"nexus-path-{Guid.NewGuid():N}");
        Directory.CreateDirectory(root);

        try
        {
            var dbPath = NexusIdentityDataPaths.ResolveDatabasePath(root);
            Assert.Contains(Path.Combine("data", "identity"), dbPath);
            Assert.EndsWith("nexus-identity.db", dbPath);
            Assert.True(Directory.Exists(Path.Combine(root, "data", "identity")));
        }
        finally
        {
            Directory.Delete(root, recursive: true);
        }
    }

    [Fact]
    public void BuildConnectionString_ContainsDataSource()
    {
        var root = Path.Combine(Path.GetTempPath(), $"nexus-conn-{Guid.NewGuid():N}");
        try
        {
            var cs = NexusIdentityDataPaths.BuildConnectionString(root);
            Assert.StartsWith("Data Source=", cs);
            Assert.Contains("nexus-identity.db", cs);
        }
        finally
        {
            if (Directory.Exists(root))
            {
                Directory.Delete(root, recursive: true);
            }
        }
    }

    [Fact]
    public void ResolveDatabasePath_UsesInstallRootBeforeRootExists()
    {
        var root = Path.Combine(Path.GetTempPath(), $"nexus-first-run-{Guid.NewGuid():N}");

        try
        {
            var dbPath = NexusIdentityDataPaths.ResolveDatabasePath(root);

            Assert.StartsWith(root, dbPath, StringComparison.OrdinalIgnoreCase);
            Assert.Contains(Path.Combine("data", "identity"), dbPath);
            Assert.True(Directory.Exists(Path.Combine(root, "data", "identity")));
        }
        finally
        {
            if (Directory.Exists(root))
            {
                Directory.Delete(root, recursive: true);
            }
        }
    }

    [Fact]
    public void ResolveDefaultDeviceName_FallsBackWhenMachineNameEmpty()
    {
        var name = NexusIdentityBootstrapService.ResolveDefaultDeviceName();
        Assert.False(string.IsNullOrWhiteSpace(name));
    }
}
