using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using StellaOps.Vexer.Export;

namespace StellaOps.Vexer.ArtifactStores.S3.Extensions;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddVexS3ArtifactClient(this IServiceCollection services, Action<S3ArtifactClientOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(configure);

        services.Configure(configure);
        services.AddSingleton(CreateS3Client);
        services.AddSingleton<IS3ArtifactClient, S3ArtifactClient>();
        return services;
    }

    private static IAmazonS3 CreateS3Client(IServiceProvider provider)
    {
        var options = provider.GetRequiredService<IOptions<S3ArtifactClientOptions>>().Value;
        var config = new AmazonS3Config
        {
            RegionEndpoint = RegionEndpoint.GetBySystemName(options.Region),
            ForcePathStyle = options.ForcePathStyle,
        };

        if (!string.IsNullOrWhiteSpace(options.ServiceUrl))
        {
            config.ServiceURL = options.ServiceUrl;
        }

        return new AmazonS3Client(config);
    }
}
