using Microsoft.EntityFrameworkCore;
using FluentValidation;
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.Behaviors;
using ColaFlow.Modules.ProjectManagement.Application.Commands.CreateProject;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Infrastructure.Persistence;
using ColaFlow.Modules.ProjectManagement.Infrastructure.Repositories;
using Microsoft.Extensions.Hosting;

namespace ColaFlow.API.Extensions;

/// <summary>
/// Extension methods for registering modules
/// </summary>
public static class ModuleExtensions
{
    /// <summary>
    /// Register ProjectManagement Module
    /// </summary>
    public static IServiceCollection AddProjectManagementModule(
        this IServiceCollection services,
        IConfiguration configuration,
        IHostEnvironment? environment = null)
    {
        // Only register PostgreSQL DbContext in non-Testing environments
        // In Testing environment, WebApplicationFactory will register InMemory provider
        if (environment == null || environment.EnvironmentName != "Testing")
        {
            // Register DbContext
            var connectionString = configuration.GetConnectionString("PMDatabase");
            services.AddDbContext<PMDbContext>(options =>
                options.UseNpgsql(connectionString));
        }

        // Register repositories
        services.AddScoped<IProjectRepository, ProjectRepository>();
        services.AddScoped<IUnitOfWork, UnitOfWork>();

        // Register MediatR handlers from Application assembly (v13.x syntax)
        services.AddMediatR(cfg =>
        {
            cfg.LicenseKey = configuration["MediatR:LicenseKey"];
            cfg.RegisterServicesFromAssembly(typeof(CreateProjectCommand).Assembly);
        });

        // Register FluentValidation validators
        services.AddValidatorsFromAssembly(typeof(CreateProjectCommand).Assembly);

        // Register pipeline behaviors
        services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));

        Console.WriteLine("[ProjectManagement] Module registered");

        return services;
    }
}
