using Microsoft.EntityFrameworkCore;

namespace RolemasterDb.App.Data;

public static class RolemasterDbInitializer
{
    public static async Task InitializeAsync(IServiceProvider services, CancellationToken cancellationToken = default)
    {
        await using var scope = services.CreateAsyncScope();
        var dbFactory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<RolemasterDbContext>>();
        await using var dbContext = await dbFactory.CreateDbContextAsync(cancellationToken);

        await dbContext.Database.EnsureCreatedAsync(cancellationToken);
        await RolemasterDbSchemaUpgrader.EnsureLatestAsync(dbContext, cancellationToken);
        RolemasterSeedData.BackfillAttackTableMetadata(dbContext);

        if (await dbContext.AttackTables.AnyAsync(cancellationToken))
        {
            await dbContext.SaveChangesAsync(cancellationToken);
            return;
        }

        RolemasterSeedData.SeedAttackStarterData(dbContext);
        await dbContext.SaveChangesAsync(cancellationToken);
    }
}
