namespace MyOffice.Web.Infrastructure;

using DbContext;

/// <summary>
/// Runs EF migrate + seed on startup with a scoped DbContext.
/// </summary>
public sealed class DatabaseInitializerHostedService : IHostedService
{
	private readonly IServiceProvider _serviceProvider;
	private readonly ILogger<DatabaseInitializerHostedService> _logger;

	public DatabaseInitializerHostedService(
		IServiceProvider serviceProvider,
		ILogger<DatabaseInitializerHostedService> logger
	)
	{
		_serviceProvider = serviceProvider;
		_logger = logger;
	}

	public async Task StartAsync(CancellationToken cancellationToken)
	{
		await using var scope = _serviceProvider.CreateAsyncScope();
		var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();

		_logger.LogInformation("Applying database migrations and seed data…");
		await DatabaseBootstrapper.InitializeAsync(db, cancellationToken);
		_logger.LogInformation("Database ready.");
	}

	public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
