using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.AIHITMainSyncer.Services;
using PARR.AIHITMainSyncer.Settings;
using PARR.Core.Common.Interfaces.RabbitServices;

namespace PARR.AIHITMainSyncer
{
    internal class AihitMainSyncer : IAihitMainSyncer
    {
        private readonly ILogger<AihitMainSyncer> logger;
        private readonly IRabbitService mqService;
        private readonly MqSettings mqSettings;
        private readonly IServiceProvider serviceProvider;

        public AihitMainSyncer(
            ILogger<AihitMainSyncer> logger,
            IRabbitService mqService,
            MqSettings mqSettings,
            IServiceProvider serviceProvider
            )
        {
            this.logger = logger;
            this.mqService = mqService;
            this.mqSettings = mqSettings;
            this.serviceProvider = serviceProvider;
        }
        public async Task StartAsync()
        {
            logger.LogInformation("Запуск сервиса синхронизации данных из АИХИТ и ПАРР.");

            var isConnected = await mqService.InitConsumerAsync(mqSettings, async (string msg) =>
            {
                using (var scope = serviceProvider.CreateScope())
                {
                    var syncerService = scope.ServiceProvider.GetRequiredService<ISyncerService>();
                    await syncerService.SyncAsync(msg);
                }

            });

            if (!isConnected)
                throw new Exception("Ошибка при подключении к RabbitMq");
        }


        public async Task StopAsync()
        {
           await mqService.DisposeAsync();
        }
    }
}
