using Microsoft.Extensions.Options; using Tiku.Application.Security; using Tiku.Application.Tenancy; namespace Tiku.Api.Background; internal sealed class DevelopmentTenantDomainLifecycleHostedService( IServiceScopeFactory scopeFactory, IOptions domainOptions, ILogger logger) : BackgroundService { private readonly DomainLifecycleOptions options = domainOptions.Value; protected override async Task ExecuteAsync(CancellationToken stoppingToken) { if (!options.EnableDevelopmentLocalhostBypass) return; var interval = TimeSpan.FromSeconds(Math.Clamp(options.PollSeconds, 1, 3600)); while (!stoppingToken.IsCancellationRequested) { try { await using var scope = scopeFactory.CreateAsyncScope(); scope.ServiceProvider.GetRequiredService() .InitializeSystem(null, "Development .localhost domain lifecycle"); var processed = await scope.ServiceProvider .GetRequiredService() .ProcessPendingAsync(stoppingToken); if (processed > 0) logger.LogInformation("Processed {DomainCount} pending Development tenant domains.", processed); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception exception) { logger.LogError(exception, "Development tenant domain lifecycle iteration failed."); } await Task.Delay(interval, stoppingToken); } } }