using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using JiShe.CollectBus.Data;
using Volo.Abp.DependencyInjection;

namespace JiShe.CollectBus.EntityFrameworkCore;

public class EntityFrameworkCoreCollectBusDbSchemaMigrator
    : ICollectBusDbSchemaMigrator, ITransientDependency
{
    private readonly IServiceProvider _serviceProvider;

    public EntityFrameworkCoreCollectBusDbSchemaMigrator(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public async Task MigrateAsync()
    {
        /* We intentionally resolving the CollectBusDbContext
         * from IServiceProvider (instead of directly injecting it)
         * to properly get the connection string of the current tenant in the
         * current scope.
         */

        await _serviceProvider
            .GetRequiredService<CollectBusDbContext>()
            .Database
            .MigrateAsync();
    }
}
