using FluentValidation;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace DocumentOperator.Application;

/// <summary>
/// Dependency Injection configuration for Application Layer
/// </summary>
public static class DependencyInjection
{
    /// <summary>
    /// Registers Application Layer services (MediatR, FluentValidation, AutoMapper, Behaviors)
    /// </summary>
    public static IServiceCollection AddApplication(this IServiceCollection services, IConfiguration configuration)
    {
        var assembly = typeof(DependencyInjection).Assembly;

        // Read LuckyPennySoft license key from appsettings.json
        var licenseKey = configuration.GetValue<string>("LuckyPennySoftLicenseKey")
            ?? throw new InvalidOperationException("LuckyPennySoftLicenseKey not found in configuration");

        // Register MediatR (scannt Assembly nach Handlers)
        services.AddMediatR(config =>
        {
            config.LicenseKey = licenseKey;
            config.RegisterServicesFromAssembly(assembly);

            // Pipeline Behaviors (Reihenfolge wichtig!)
            config.AddOpenBehavior(typeof(Common.Behaviors.ValidationBehavior<,>));
            config.AddOpenBehavior(typeof(Common.Behaviors.LoggingBehavior<,>));
        });

        // Register FluentValidation (scannt Assembly nach Validators)
        services.AddValidatorsFromAssembly(assembly);

        // Register AutoMapper (scannt Assembly nach Profiles)
        services.AddAutoMapper(cfg => {
            cfg.LicenseKey = licenseKey;
        }, typeof(Common.Mapping.MappingProfile));

        return services;
    }
}
