using BLL.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace CONTROLLER.BackgroundServices
{
    /// <summary>
    /// 面单PDF缓存定时任务服务
    /// </summary>
    public class LabelPdfCacheBackgroundService : BackgroundService
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<LabelPdfCacheBackgroundService> _logger;
        private const int TaskIntervalMinutes = 5; // 每5分钟执行一次

        public LabelPdfCacheBackgroundService(
            IServiceProvider serviceProvider,
            ILogger<LabelPdfCacheBackgroundService> logger)
        {
            _serviceProvider = serviceProvider;
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Label PDF Cache Background Service is starting");

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    _logger.LogInformation("Starting label PDF cache processing task");
                    
                    // 创建作用域获取服务
                    using var scope = _serviceProvider.CreateScope();
                    var cacheService = scope.ServiceProvider.GetRequiredService<ILabelPdfCacheService>();
                    
                    // 处理待处理任务
                    var successCount = await cacheService.ProcessPendingTasksAsync();
                    
                    _logger.LogInformation("Completed label PDF cache processing task, success count: {count}", successCount);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error occurred in label PDF cache background service");
                }

                // 等待指定时间后再次执行
                await Task.Delay(TimeSpan.FromMinutes(TaskIntervalMinutes), stoppingToken);
            }

            _logger.LogInformation("Label PDF Cache Background Service is stopping");
        }
    }
}
