using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ChatService.Domain.AggregatesModel.UserAggregate;
using ChatService.Domain.AggregatesModel.ConversationAggregate;
using ChatService.Domain.Contracts;
using ChatService.Infrastructure.Idempotency;
using ChatService.Infrastructure.Repositories;
using ChatService.Infrastructure.Services;

namespace ChatService.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<ChatServiceContext>(options =>
        {
            var connectionString = configuration.GetConnectionString("DefaultConnection")
                ?? configuration["DATABASE_URL"]
                ?? throw new InvalidOperationException("Connection string not configured");

            options.UseNpgsql(connectionString, npgsqlOptions =>
            {
                npgsqlOptions.MigrationsAssembly(typeof(ChatServiceContext).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<IChatUserRepository, ChatUserRepository>();
        services.AddScoped<IConversationRepository, ConversationRepository>();

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

        // EN: Register AI service / VI: Đăng ký AI service
        services.Configure<AIServiceOptions>(configuration.GetSection(AIServiceOptions.SectionName));
        
        var openAiApiKey = configuration["OPENAI_API_KEY"] 
            ?? Environment.GetEnvironmentVariable("OPENAI_API_KEY");
        
        if (!string.IsNullOrEmpty(openAiApiKey))
        {
            services.AddHttpClient<IAIService, AIService>(client =>
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {openAiApiKey}");
            });
        }
        else
        {
            // EN: Use null implementation when API key is not configured
            // VI: Sử dụng null implementation khi API key chưa được cấu hình
            services.AddSingleton<IAIService, NullAIService>();
        }

        return services;
    }
}

