using Microsoft.EntityFrameworkCore;

namespace Indotalent.Infrastructure.Database;

public static class DI
{
    public static IServiceCollection AddDatabaseService(this IServiceCollection services, IConfiguration configuration)
    {
        var dbSettings = configuration.GetSection("DatabaseSettings").Get<DatabaseSettingsModel>();

        if (dbSettings?.MsSQL?.IsUsed == true)
        {
            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(
                    dbSettings.MsSQL.ConnectionString,
                    sqlOptions =>
                    {
                        sqlOptions.CommandTimeout(dbSettings.MsSQL.TimeoutInSeconds);
                    }
                )
            );
        }
        else if (dbSettings?.PostgreSQL?.IsUsed == true)
        {
            services.AddDbContext<AppDbContext>(options =>
                options.UseNpgsql(
                    dbSettings.PostgreSQL.ConnectionString,
                    npgsqlOptions =>
                    {
                        npgsqlOptions.CommandTimeout(dbSettings.PostgreSQL.TimeoutInSeconds);
                    }
                )
            );
        }
        else if (dbSettings?.MySQL?.IsUsed == true)
        {
            services.AddDbContext<AppDbContext>(options =>
                options.UseMySQL(
                    dbSettings.MySQL.ConnectionString,
                    mySqlOptions =>
                    {
                        mySqlOptions.CommandTimeout(dbSettings.MySQL.TimeoutInSeconds);
                        mySqlOptions.MigrationsAssembly(typeof(AppDbContext).Assembly.FullName);
                    }
                )
            );
        }

        services.AddScoped<DatabaseService>();

        return services;
    }
}