using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using BookingService.Domain.AggregatesModel.AppointmentAggregate;
using BookingService.Domain.AggregatesModel.TherapistAggregate;
using BookingService.Infrastructure.Repositories;

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

            options.UseNpgsql(connectionString, npgsqlOptions =>
            {
                npgsqlOptions.MigrationsAssembly(typeof(BookingContext).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<IAppointmentRepository, AppointmentRepository>();
        services.AddScoped<IResourceRepository, ResourceRepository>();
        services.AddScoped<IStaffScheduleRepository, StaffScheduleRepository>();
        services.AddScoped<ITherapistRepository, TherapistRepository>();

        // EN: Idempotency services not registered — no handler uses IRequestManager
        // VI: Idempotency services không được đăng ký — không có handler nào dùng IRequestManager

        return services;
    }
}
