namespace Health.WebApi.BackgroundServices;

/// <summary>
/// 数据清理后台服务（每小时检查一次）
/// </summary>
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 db = scope.ServiceProvider.GetRequiredService<AppDbContext>();

                // 清理 30 天前的对话记录
                var cutoff = DateTime.UtcNow.AddDays(-30);
                var oldConversations = await db.Conversations
                    .Where(c => c.CreatedAt < cutoff)
                    .ToListAsync(stoppingToken);

                if (oldConversations.Count > 0)
                {
                    db.Conversations.RemoveRange(oldConversations);
                    await db.SaveChangesAsync(stoppingToken);
                    _logger.LogInformation("清理 {Count} 条过期对话", oldConversations.Count);
                }

                // 清理过期验证码
                var expiredCodes = await db.VerificationCodes
                    .Where(v => v.ExpiresAt < DateTime.UtcNow)
                    .ToListAsync(stoppingToken);

                if (expiredCodes.Count > 0)
                {
                    db.VerificationCodes.RemoveRange(expiredCodes);
                    await db.SaveChangesAsync(stoppingToken);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "数据清理异常");
            }

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