namespace GmRelay.Bot.Tests.Web;

public sealed class PortfolioCoverRuntimeWiringTests
{
    [Fact]
    public async Task Program_ShouldRegisterPortfolioCoverStorage()
    {
        var program = await ReadRepositoryFileAsync("src/GmRelay.Web/Program.cs");

        Assert.Contains("AddPortfolioCoverStorage", program, StringComparison.Ordinal);
        Assert.Contains("UsePortfolioCoverFiles", program, StringComparison.Ordinal);
    }

    [Fact]
    public async Task Compose_ShouldMountPortfolioCoversVolumeAndPassStoragePath()
    {
        var compose = await ReadRepositoryFileAsync("compose.yaml");

        Assert.Contains("PortfolioCovers__StoragePath=/app/portfolio-covers", compose, StringComparison.Ordinal);
        Assert.Contains("portfolio_covers:/app/portfolio-covers", compose, StringComparison.Ordinal);
    }

    [Fact]
    public async Task Dockerfile_ShouldCreateAndChownPortfolioCoversDirectory()
    {
        var dockerfile = await ReadRepositoryFileAsync("src/GmRelay.Web/Dockerfile");

        Assert.Contains("mkdir -p /app/dataprotection-keys /app/portfolio-covers", dockerfile, StringComparison.Ordinal);
        Assert.Contains("chown -R $APP_UID:$APP_UID /app/dataprotection-keys /app/portfolio-covers", dockerfile, StringComparison.Ordinal);
    }

    [Fact]
    public async Task DevelopmentSettings_ShouldConfigurePortfolioCoversStoragePath()
    {
        var developmentSettings = await ReadRepositoryFileAsync("src/GmRelay.Web/appsettings.Development.json");

        Assert.Contains("../../artifacts/portfolio-covers", developmentSettings, StringComparison.Ordinal);
    }

    [Fact]
    public async Task EnvExample_ShouldDocumentPortfolioCoversVolumeName()
    {
        var envExample = await ReadRepositoryFileAsync(".env.example");

        Assert.Contains("PORTFOLIO_COVERS_VOLUME_NAME", envExample, StringComparison.Ordinal);
    }

    [Fact]
    public async Task Compose_ShouldDeclarePortfolioCoversNamedVolume()
    {
        var compose = await ReadRepositoryFileAsync("compose.yaml");

        Assert.Contains("portfolio_covers:", compose, StringComparison.Ordinal);
        Assert.Contains("PORTFOLIO_COVERS_VOLUME_NAME", compose, StringComparison.Ordinal);
    }

    private static async Task<string> ReadRepositoryFileAsync(string relativePath)
    {
        var directory = new DirectoryInfo(AppContext.BaseDirectory);
        while (directory is not null)
        {
            var candidate = Path.Combine(directory.FullName, relativePath);
            if (File.Exists(candidate))
            {
                return await File.ReadAllTextAsync(candidate);
            }

            directory = directory.Parent;
        }

        throw new FileNotFoundException($"Could not locate repository file '{relativePath}'.");
    }
}
