using Microsoft.EntityFrameworkCore;
using NexusIdentity.Api.Data;

namespace NexusIdentity.Api.Data;

public static class DatabaseInitializer
{
    public static async Task EnsureSchemaAsync(IdentityDbContext db)
    {
        if (await SchemaReadyAsync(db))
        {
            return;
        }

        try
        {
            await db.Database.MigrateAsync();
            if (await SchemaReadyAsync(db))
            {
                return;
            }
        }
        catch
        {
            // Migration assembly may be unavailable in POC builds — fall back below.
        }

        // EnsureCreated skips when __EFMigrationsHistory exists without app tables (failed migrate).
        await db.Database.EnsureDeletedAsync();
        await db.Database.EnsureCreatedAsync();
    }

    private static async Task<bool> SchemaReadyAsync(IdentityDbContext db)
    {
        try
        {
            return await db.Organizations.AnyAsync();
        }
        catch
        {
            return false;
        }
    }
}
