using System;
using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace JiShe.CollectBus.EntityFrameworkCore;

/* This class is needed for EF Core console commands
 * (like Add-Migration and Update-Database commands) */
public class CollectBusDbContextFactory : IDesignTimeDbContextFactory<CollectBusDbContext>
{
    public CollectBusDbContext CreateDbContext(string[] args)
    {
        var configuration = BuildConfiguration();
        
        CollectBusEfCoreEntityExtensionMappings.Configure();

        var builder = new DbContextOptionsBuilder<CollectBusDbContext>()
            .UseMySql(configuration.GetConnectionString("Default"), MySqlServerVersion.LatestSupportedServerVersion);
        
        return new CollectBusDbContext(builder.Options);
    }

    private static IConfigurationRoot BuildConfiguration()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../JiShe.CollectBus.DbMigrator/"))
            .AddJsonFile("appsettings.json", optional: false);

        return builder.Build();
    }
}
