using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.Core.Common.Interfaces;
using PARR.Core.Services.TaskServices.Interfaces;
using PARR.Core.Services.Workload.Interfaces;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Settings;

namespace PARR.Core.Services.Workload.Implementations
{
    internal class WorkloadIntervalService : IWorkloadIntervalService
    {
        private readonly ILogger<WorkloadIntervalService> logger;
        private readonly IIntervalService intervalService;
        private readonly IServiceProvider serviceProvider;

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

        public async Task StartAsync(TimeSpan interval, IMqSettings mqSettings)
        {
            logger.LogInformation("Запуск сервиса формирования кэш отчетов Workload по интервалу.");

            await intervalService.IntervalInitAsync(async () =>
            {

                await using (var scope = serviceProvider.CreateAsyncScope())
                {
                    var taskManagementService = scope.ServiceProvider.GetRequiredService<ITaskManagementService>();

                    var initiator = new HistoryInitiator { InitiatorParrComponentId = Domain.Enums.ParrComponentsEnum.WorkloadBuilder, InitiatorComment = $"Генерация кэш workload по интервалу '{interval}'" };

                    try
                    {
                        var taskId = await taskManagementService.CreateTaskAsync<object?>(Domain.Enums.TaskTypeEnum.Workload, default, initiator, mqSettings);
                        logger.LogInformation("Создана задача {taskId} на формирование кэш отчета.", taskId);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "Ошибка при отправке задания на формирование кэш отчета.");
                    }
                }

            }, interval);
        }
    }
}
