using Health.Application.Maintenance;

namespace Health.WebApi.BackgroundServices;

public sealed class CleanupService(IServiceScopeFactory scopeFactory, ILogger<CleanupService> logger) : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
    private readonly ILogger<CleanupService> _logger = logger;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using var scope = _scopeFactory.CreateScope();
                var maintenance = scope.ServiceProvider.GetRequiredService<IMaintenanceService>();
                var result = await maintenance.CleanupAsync(DateTime.UtcNow, stoppingToken);
                if (result.Conversations + result.VerificationCodes + result.BackgroundTasks > 0)
                {
                    _logger.LogInformation(
                        "自动清理完成: 会话 {Conversations}, 验证码 {Codes}, 后台任务 {Tasks}",
                        result.Conversations,
                        result.VerificationCodes,
                        result.BackgroundTasks);
                }
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "数据清理异常");
            }

            await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
        }
    }
}
