using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Minio;
using Knot.Shared.Kernel.Storage;
using Knot.Shared.Kernel.Security;
using Knot.Modules.Storage.Infrastructure.Storage;
using System;

namespace Knot.Modules.Storage;

public static class DependencyInjection
{
    public static IServiceCollection AddStorageModule(this IServiceCollection services, IConfiguration configuration)
    {
        var s3Endpoint = configuration["S3_ENDPOINT"] ?? "minio:9000";
        var s3AccessKey = configuration["S3_ACCESS_KEY"] ?? "admin";
        var s3SecretKey = configuration["S3_SECRET_KEY"] ?? "KnotSuperSecretMinioPassword";
        var s3Bucket = configuration["S3_BUCKET"] ?? "knot-uploads";

        services.AddMinio(configureClient => configureClient
            .WithEndpoint(s3Endpoint)
            .WithCredentials(s3AccessKey, s3SecretKey)
            .WithSSL(false)
            .Build());

        services.AddScoped<IFileStorageService>(provider =>
        {
            var minioClient = provider.GetRequiredService<IMinioClient>();
            var encService = provider.GetRequiredService<IEncryptionService>();
            return new S3FileStorageService(minioClient, encService, s3Bucket);
        });

        return services;
    }
}
