using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MembershipService.Domain.AggregatesModel.ExperienceAggregate;
using MembershipService.Domain.AggregatesModel.LevelAggregate;
using MembershipService.Domain.AggregatesModel.MemberAggregate;
using MembershipService.Infrastructure.ExternalServices;
using MembershipService.Infrastructure.Idempotency;
using MembershipService.Infrastructure.Repositories;

namespace MembershipService.Infrastructure;

/// <summary>
/// EN: Dependency injection extensions for Infrastructure layer.
/// VI: Extensions dependency injection cho lớp Infrastructure.
/// </summary>
public static class DependencyInjection
{
    /// <summary>
    /// EN: Add infrastructure services to the DI container.
    /// VI: Thêm các services infrastructure vào DI container.
    /// </summary>
    public static IServiceCollection AddInfrastructure(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        // EN: Add DbContext with PostgreSQL / VI: Thêm DbContext với PostgreSQL
        services.AddDbContext<MembershipServiceContext>(options =>
        {
            var connectionString = configuration.GetConnectionString("DefaultConnection")
                ?? configuration["DATABASE_URL"]
                ?? throw new InvalidOperationException("Connection string not configured");

            options.UseNpgsql(connectionString, npgsqlOptions =>
            {
                npgsqlOptions.MigrationsAssembly(typeof(MembershipServiceContext).Assembly.FullName);
                npgsqlOptions.EnableRetryOnFailure(
                    maxRetryCount: 5,
                    maxRetryDelay: TimeSpan.FromSeconds(30),
                    errorCodesToAdd: null);
            });

            // EN: Enable sensitive data logging in development only
            // VI: Chỉ bật sensitive data logging trong development
            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
            {
                options.EnableSensitiveDataLogging();
                options.EnableDetailedErrors();
            }
        });

        // EN: Register repositories / VI: Đăng ký repositories
        services.AddScoped<IMemberRepository, MemberRepository>();
        services.AddScoped<ILevelDefinitionRepository, LevelDefinitionRepository>();
        services.AddScoped<IExperienceTransactionRepository, ExperienceTransactionRepository>();

        // EN: Register idempotency services / VI: Đăng ký idempotency services
        services.AddScoped<IRequestManager, RequestManager>();

        // EN: Configure IAM Service Client / VI: Cấu hình IAM Service Client
        services.Configure<IamServiceSettings>(
            configuration.GetSection(IamServiceSettings.SectionName));

        // EN: Register HttpClient for IAM Service / VI: Đăng ký HttpClient cho IAM Service
        services.AddHttpClient<IIamServiceClient, HttpIamServiceClient>((sp, client) =>
        {
            var settings = configuration.GetSection(IamServiceSettings.SectionName)
                .Get<IamServiceSettings>() ?? new IamServiceSettings();
            
            client.BaseAddress = new Uri(settings.BaseUrl);
            client.Timeout = TimeSpan.FromSeconds(settings.TimeoutSeconds);
            client.DefaultRequestHeaders.Add("Accept", "application/json");
        })
        .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
        {
            // EN: Allow self-signed certificates in development
            // VI: Cho phép self-signed certificates trong development
            ServerCertificateCustomValidationCallback = 
                HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
        });

        return services;
    }
}
