using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using AdsTrackingService.Domain.AggregatesModel.TrackingPixelAggregate;
using AdsTrackingService.Domain.AggregatesModel.ConversionAggregate;
using AdsTrackingService.Domain.AggregatesModel.AttributionAggregate;
using AdsTrackingService.Infrastructure.Repositories;
using AdsTrackingService.Infrastructure.Idempotency;

namespace AdsTrackingService.Infrastructure;

public static class DependencyInjection
{
    public static IServiceCollection AddInfrastructure(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        services.AddDbContext<AdsTrackingServiceContext>(options =>
        {
            var connectionString = configuration.GetConnectionString("DefaultConnection")
                ?? configuration["DATABASE_URL"]
                ?? throw new InvalidOperationException("Connection string not configured");

            options.UseNpgsql(connectionString, npgsqlOptions =>
            {
                npgsqlOptions.MigrationsAssembly(typeof(AdsTrackingServiceContext).Assembly.FullName);
                npgsqlOptions.EnableRetryOnFailure(5, TimeSpan.FromSeconds(30), null);
            });

            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
            {
                options.EnableSensitiveDataLogging();
                options.EnableDetailedErrors();
            }
        });

        services.AddScoped<IRequestManager, RequestManager>();
        // EN: Register repositories / VI: Đăng ký repositories
        services.AddScoped<ITrackingPixelRepository, TrackingPixelRepository>();
        services.AddScoped<IConversionRepository, ConversionRepository>();
        services.AddScoped<IAttributionRepository, AttributionRepository>();

        return services;
    }
}
