using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using FacebookService.Domain.AggregatesModel.CustomerAggregate;
using FacebookService.Domain.AggregatesModel.ConversationAggregate;
using FacebookService.Domain.AggregatesModel.ChatbotAggregate;
using FacebookService.Infrastructure.Idempotency;
using FacebookService.Infrastructure.Repositories;
using FacebookService.Infrastructure.ExternalServices;
using Polly;
using Polly.Extensions.Http;

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

            options.UseNpgsql(connectionString, npgsqlOptions =>
            {
                npgsqlOptions.MigrationsAssembly(typeof(FacebookServiceContext).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<ICustomerRepository, CustomerRepository>();
        services.AddScoped<IConversationRepository, ConversationRepository>();
        services.AddScoped<IChatbotFlowRepository, ChatbotFlowRepository>();
        services.AddScoped<IAIChatbotConfigRepository, AIChatbotConfigRepository>();

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

        // EN: Register Facebook Messenger client / VI: Đăng ký Facebook Messenger client
        services.AddHttpClient<IFacebookMessengerClient, FacebookMessengerClient>()
            .AddPolicyHandler(FacebookMessengerClient.GetRetryPolicy());

        // EN: Register AI clients / VI: Đăng ký AI clients
        var aiProvider = configuration["AI:Provider"] 
            ?? configuration["AI_PROVIDER"]
            ?? "openai";

        if (aiProvider.Equals("azure", StringComparison.OrdinalIgnoreCase) ||
            aiProvider.Equals("azureopenai", StringComparison.OrdinalIgnoreCase))
        {
            services.AddHttpClient<IAIClient, AzureOpenAIClient>()
                .AddPolicyHandler(GetAIRetryPolicy());
        }
        else
        {
            services.AddHttpClient<IAIClient, OpenAIClient>()
                .AddPolicyHandler(GetAIRetryPolicy());
        }

        return services;
    }

    private static IAsyncPolicy<HttpResponseMessage> GetAIRetryPolicy()
    {
        return HttpPolicyExtensions
            .HandleTransientHttpError()
            .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
            .WaitAndRetryAsync(3, retryAttempt =>
                TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
    }
}
