using Microsoft.Extensions.Options;
using Tiku.Application.Security;
using Tiku.Application.Tenancy;

namespace Tiku.Api.Background;

internal sealed class DevelopmentTenantDomainLifecycleHostedService(
    IServiceScopeFactory scopeFactory,
    IOptions<DomainLifecycleOptions> domainOptions,
    ILogger<DevelopmentTenantDomainLifecycleHostedService> 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<ITenantContextInitializer>()
                    .InitializeSystem(null, "Development .localhost domain lifecycle");
                var processed = await scope.ServiceProvider
                    .GetRequiredService<ITenantDomainLifecycleService>()
                    .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);
        }
    }
}