namespace RolemasterDb.App.Features;

public sealed class CriticalImportArtifactLocator
{
    public CriticalImportArtifactLocator(IHostEnvironment hostEnvironment)
    {
        ArtifactsRootPath = DiscoverArtifactsRootPath(hostEnvironment.ContentRootPath);
    }

    public string ArtifactsRootPath { get; }

    public string? ResolveStoredPath(string? relativePath)
    {
        if (string.IsNullOrWhiteSpace(relativePath))
        {
            return null;
        }

        var candidate = Path.GetFullPath(Path.Combine(
            ArtifactsRootPath,
            relativePath.Replace('/', Path.DirectorySeparatorChar)));

        return candidate.StartsWith(ArtifactsRootPath, StringComparison.OrdinalIgnoreCase)
            ? candidate
            : null;
    }

    private static string DiscoverArtifactsRootPath(string contentRootPath)
    {
        var probe = new DirectoryInfo(contentRootPath);

        while (probe is not null)
        {
            if (File.Exists(Path.Combine(probe.FullName, "RolemasterDB.slnx")))
            {
                return Path.Combine(probe.FullName, "src", "RolemasterDb.App", "import-artifacts", "critical");
            }

            probe = probe.Parent;
        }

        return Path.Combine(contentRootPath, "import-artifacts", "critical");
    }
}