using Microsoft.Extensions.Options;
using TakeoutSaaS.Module.Storage.Abstractions;
using TakeoutSaaS.Module.Storage.Options;

namespace TakeoutSaaS.Module.Storage.Services;

/// <summary>
/// 存储提供商解析器，实现基于配置的提供商选择。
/// </summary>
public sealed class StorageProviderResolver(IOptionsMonitor<StorageOptions> optionsMonitor, IEnumerable<IObjectStorageProvider> providers)
    : IStorageProviderResolver
{
    private readonly IDictionary<StorageProviderKind, IObjectStorageProvider> _providerMap =
        providers.ToDictionary(x => x.Kind, x => x);

    /// <inheritdoc />
    public IObjectStorageProvider Resolve(StorageProviderKind? provider = null)
    {
        var target = provider ?? optionsMonitor.CurrentValue.Provider;
        if (_providerMap.TryGetValue(target, out var instance))
        {
            return instance;
        }

        throw new InvalidOperationException($"未注册存储提供商：{target}");
    }
}
