using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Modules.Library.Application.Gateways;
using Modules.Library.Database.Database;
using Modules.Library.Database.GatewaysImplementations;
using Modules.Library.Database.Repositories;
using System.Reflection;

namespace Modules.Library.Database;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddDatabase(this IServiceCollection services, string? connectionString)
    {
        if (string.IsNullOrWhiteSpace(connectionString)) throw new ArgumentNullException(nameof(connectionString));
        services.AddDbContext<LibraryDbContext>(options =>
        {
            options.UseNpgsql(connectionString, q =>
            {
                q.MigrationsAssembly(Assembly.GetAssembly(typeof(LibraryDbContext))!.GetName().Name);
                q.MigrationsHistoryTable("__Migrations");
            });
            //options.UseNpgsql(connectionString);
            //AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); //Включаем UTC-время.
            //options.UseLazyLoadingProxies(); // lazy loading
        });
        AddRepositories(services);
        AddGateways(services);
        return services;
    }

    //public static IServiceCollection AddDatabase(this IServiceCollection services, string connectionString, string? databaseName)
    //{
    //    AddMongoDb(services, connectionString, databaseName);
    //    //services.AddScoped<MongoDbContext>();
    //    services.AddScoped<LibraryDbContext>(q =>
    //    {
    //        var context = new LibraryDbContext(q.GetRequiredService<IMongoDatabase>());
    //        context.Initialize();
    //        return context;
    //    });
    //    AddRepositories(services);
    //    AddGateways(services);
    //    return services;
    //}

    private static void AddRepositories(IServiceCollection services)
    {
        services.AddScoped<AnimeTitleRepository>();
        services.AddScoped<AnimeSeasonRepository>();
        services.AddScoped<AnimeEpisodeRepository>();
        services.AddScoped<GenreRepository>();
        services.AddScoped<LanguageRepository>();
        services.AddScoped<MediaInfoRepository>();
    }

    private static void AddGateways(IServiceCollection services)
    {
        services.AddScoped<IAnimeTitleGateway, AnimeTitleGateway>();
        services.AddScoped<IAnimeSeasonGateway, AnimeSeasonGateway>();
        services.AddScoped<IAnimeEpisodeGateway, AnimeEpisodeGateway>();
        services.AddScoped<IGenreGateway, GenreGateway>();
        services.AddScoped<ILanguageGateway, LanguageGateway>();
        //services.AddScoped<IMediaInfoGateway, MediaInfoGateway>();
    }
}