using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Knot.Shared.Kernel;
using Knot.Shared.Kernel.Security;
using Knot.Shared.Kernel.Storage;
using Knot.Shared.Infrastructure.Persistence;
using Knot.Shared.Infrastructure.Statistics;
using Microsoft.EntityFrameworkCore;
using Minio;
using System;

namespace Knot.Shared.Infrastructure;

public static class DependencyInjection
{
    public static IServiceCollection AddSharedInfrastructure(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddHttpContextAccessor();
        services.AddScoped<IUserContext, UserContext>();

        // Настройка шифрования
        var masterKey = configuration["KNOT_MASTER_ENCRYPTION_KEY"]
                        ?? throw new ArgumentNullException("KNOT_MASTER_ENCRYPTION_KEY is missing in env.");

        services.AddSingleton<IEncryptionService>(new AesEncryptionService(masterKey));



        // Настройка System Database
        var connectionString = configuration.GetConnectionString("DefaultConnection")
            ?? configuration["DATABASE_URL"]
            ?? throw new ArgumentNullException("Database connection string not found.");

        services.AddDbContext<SystemDbContext>(options =>
            options.UseNpgsql(connectionString));

        services.AddMemoryCache();
        
        services.AddScoped<Knot.Shared.Kernel.Services.IStatisticsService, StatisticsService>();

        services.AddHostedService<StatisticsWorker>();

        return services;
    }
}
