using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Dapper;

namespace Infrastructure.Extensions
{
    /// <summary>
    /// Dependency injection extensions for Infrastructure layer
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// Add Infrastructure layer services to the dependency injection container
        /// </summary>
        /// <param name="services">The service collection</param>
        /// <param name="configuration">The application configuration</param>
        /// <returns>The service collection for chaining</returns>
        public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
        {
            var connectionString = configuration.GetConnectionString("DefaultConnection")
                ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found");

            // Ensure Dapper maps snake_case columns (e.g., study_id) to PascalCase properties (StudyId)
            DefaultTypeMap.MatchNamesWithUnderscores = true;

            // Register all repositories by group
{% for group, tables in Groups.items() %}
            // {{ group }} group repositories
{% for table in tables -%}
{% set ns = "." + group if group != "General" else "" -%}
            services.AddScoped<Core.Interfaces{{ ns }}.I{{ table.TableNamePascal }}Repository>(sp => 
                new Infrastructure.Data{{ ns }}.{{ table.TableNamePascal }}Repository(connectionString));
{% endfor %}
{% endfor %}

            // Add other infrastructure services here
            // services.AddScoped<IEmailProvider, SmtpEmailProvider>();
            // services.AddScoped<IFileStorage, LocalFileStorage>();
            // services.AddScoped<ICacheService, RedisCacheService>();

            return services;
        }
    }
}