using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PARR.Core.Common.Interfaces;
using PARR.Core.Services.TaskServices.Interfaces;
using PARR.Domain.Settings;

namespace PARR.Core.Services.TaskServices.ReconciliationHosted
{
    /// <summary>
    /// Фоновая задача для периодического запуска Reconciliation Job. 
    /// Обработка зависших задач.
    /// </summary>
    internal class ReconciliationHostedService : BackgroundService
    {
        // Это реализация воркера, подключается напрямую в воркер

        private readonly ILogger<ReconciliationHostedService> logger;
        private readonly IReconciliationSettings reconciliationSettings;
        private readonly IServiceProvider serviceProvider;
        private readonly IIntervalService intervalService;

        public ReconciliationHostedService(
            ILogger<ReconciliationHostedService> logger,
            IReconciliationSettings reconciliationSettings,
            IServiceProvider serviceProvider,
            IIntervalService intervalService
            )
        {
            this.logger = logger;
            this.reconciliationSettings = reconciliationSettings;
            this.serviceProvider = serviceProvider;
            this.intervalService = intervalService;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await intervalService.IntervalInitAsync(async () =>
            {
                await using (var scope = serviceProvider.CreateAsyncScope())
                {
                    var reconciliationService = scope.ServiceProvider.GetRequiredService<ITaskReconciliationService>();

                    // Запускаем проверку
                    var report = await reconciliationService.RunAsync();

                    if (report.HasChanged)
                        logger.LogInformation("Reconciliation Job выполнен. Проверено: {Checked}, Исправлено: {Fixed}", report.CheckedCount, report.FixedCount);
                }

            }, reconciliationSettings.CheckInterval);
        }
    }
}
