namespace TakeoutSaaS.TenantApi.Services;

/// <summary>
/// 地理定位自动重试后台服务。
/// </summary>
public sealed class GeoLocationRetryBackgroundService(
    IServiceScopeFactory serviceScopeFactory,
    ILogger<GeoLocationRetryBackgroundService> logger) : BackgroundService
{
    private static readonly TimeSpan PollingInterval = TimeSpan.FromMinutes(1);

    /// <inheritdoc />
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using var scope = serviceScopeFactory.CreateScope();
                var orchestrator = scope.ServiceProvider.GetRequiredService<GeoLocationOrchestrator>();
                var processedCount = await orchestrator.ProcessPendingAsync(stoppingToken);
                if (processedCount > 0)
                {
                    logger.LogInformation("地理定位重试任务完成，处理记录数：{Count}", processedCount);
                }
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception exception)
            {
                logger.LogError(exception, "地理定位重试任务执行失败");
            }

            try
            {
                await Task.Delay(PollingInterval, stoppingToken);
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
        }
    }
}
