using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TakeoutSaaS.Application.Dictionary.Abstractions;
using TakeoutSaaS.Domain.Dictionary.Repositories;
using TakeoutSaaS.Domain.SystemParameters.Repositories;
using TakeoutSaaS.Infrastructure.Common.Extensions;
using TakeoutSaaS.Infrastructure.Dictionary.ImportExport;
using TakeoutSaaS.Infrastructure.Dictionary.Persistence;
using TakeoutSaaS.Infrastructure.Dictionary.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;

namespace TakeoutSaaS.Infrastructure.Dictionary.Extensions;

/// <summary>
/// 字典基础设施注册扩展。
/// </summary>
public static class DictionaryServiceCollectionExtensions
{
    /// <summary>
    /// 注册字典模块基础设施。
    /// </summary>
    /// <param name="services">服务集合。</param>
    /// <param name="configuration">配置源。</param>
    /// <returns>服务集合。</returns>
    /// <exception cref="InvalidOperationException">缺少数据库配置时抛出。</exception>
    public static IServiceCollection AddDictionaryInfrastructure(this IServiceCollection services, IConfiguration configuration)
    {
        // 1. 注册数据库上下文
        services.AddDatabaseInfrastructure(configuration);
        services.AddPostgresDbContext<DictionaryDbContext>(DatabaseConstants.DictionaryDataSource);

        // 2. 注册仓储
        services.AddScoped<IDictionaryRepository, EfDictionaryRepository>();
        services.AddScoped<IDictionaryGroupRepository, DictionaryGroupRepository>();
        services.AddScoped<IDictionaryItemRepository, DictionaryItemRepository>();
        services.AddScoped<ITenantDictionaryOverrideRepository, TenantDictionaryOverrideRepository>();
        services.AddScoped<IDictionaryLabelOverrideRepository, DictionaryLabelOverrideRepository>();
        services.AddScoped<IDictionaryImportLogRepository, DictionaryImportLogRepository>();
        services.AddScoped<ICacheInvalidationLogRepository, CacheInvalidationLogRepository>();
        services.AddScoped<ISystemParameterRepository, EfSystemParameterRepository>();

        // 3. 注册导入导出解析器
        services.AddScoped<ICsvDictionaryParser, CsvDictionaryParser>();
        services.AddScoped<IJsonDictionaryParser, JsonDictionaryParser>();

        return services;
    }
}
