📄 MatDenDagen/Infrastructure/Storage/BlobStorage/BlobStorageOptions.cs
using System.IO;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace MatDenDagen.Infrastructure.Storage.BlobStorage;

public sealed class BlobStorageOptions
{
    public required string BlobDirectory { get; set; }
}

file sealed class BlobStorageOptionsValidator : IValidateOptions<BlobStorageOptions>
{
    public ValidateOptionsResult Validate(string? name, BlobStorageOptions options)
    {
        var builder = new ValidateOptionsResultBuilder();

        ValidateUploadsPath(name, options.BlobDirectory, builder);

        return builder.Build();
    }

    private static void ValidateUploadsPath(string? name, string uploadsPath, ValidateOptionsResultBuilder builder)
    {
        string propertyName = string.IsNullOrEmpty(name)
            ? nameof(BlobStorageOptions.BlobDirectory)
            : $"{name}.{nameof(BlobStorageOptions.BlobDirectory)}";

        if (string.IsNullOrWhiteSpace(uploadsPath))
        {
            builder.AddError("Cannot be null or empty.", propertyName);
            return;
        }

        if (!Directory.Exists(uploadsPath))
        {
            builder.AddError("Directory must exist.", propertyName);
            return;
        }
    }
}

public static class BlobStorageOptionsServiceExtensions
{
    public static IServiceCollection AddBlobStorageOptions(this IServiceCollection services)
    {
        services.AddOptions<BlobStorageOptions>().BindConfiguration("Storage").ValidateOnStart();
        services.AddTransient<IValidateOptions<BlobStorageOptions>, BlobStorageOptionsValidator>();
        return services;
    }
}