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

namespace TakeoutSaaS.Module.Storage.Providers;

/// <summary>
/// 七牛云 Kodo（S3 兼容网关）存储提供商。
/// </summary>
public sealed class QiniuKodoStorageProvider(IOptionsMonitor<StorageOptions> optionsMonitor)
    : S3StorageProviderBase
{
    private StorageOptions CurrentOptions => optionsMonitor.CurrentValue;

    /// <inheritdoc />
    public override StorageProviderKind Kind => StorageProviderKind.QiniuKodo;

    /// <inheritdoc />
    protected override string Bucket => CurrentOptions.QiniuKodo.Bucket;

    /// <inheritdoc />
    protected override string ServiceUrl => string.IsNullOrWhiteSpace(CurrentOptions.QiniuKodo.Endpoint)
        ? $"{(CurrentOptions.QiniuKodo.UseHttps ? "https" : "http")}://s3.qiniucs.com"
        : CurrentOptions.QiniuKodo.Endpoint!;

    /// <inheritdoc />
    protected override string AccessKey => CurrentOptions.QiniuKodo.AccessKey;

    /// <inheritdoc />
    protected override string SecretKey => CurrentOptions.QiniuKodo.SecretKey;

    /// <inheritdoc />
    protected override bool UseHttps => CurrentOptions.QiniuKodo.UseHttps;

    /// <inheritdoc />
    protected override bool ForcePathStyle => true;

    /// <inheritdoc />
    protected override string? CdnBaseUrl => !string.IsNullOrWhiteSpace(CurrentOptions.QiniuKodo.DownloadDomain)
        ? CurrentOptions.QiniuKodo.DownloadDomain
        : CurrentOptions.CdnBaseUrl;

    /// <inheritdoc />
    protected override TimeSpan SignedUrlExpiry
    {
        get
        {
            var minutes = CurrentOptions.QiniuKodo.SignedUrlExpirationMinutes
                          ?? CurrentOptions.Security.DefaultUrlExpirationMinutes;
            return TimeSpan.FromMinutes(Math.Max(1, minutes));
        }
    }
}
