using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Domain.Entities.Job;

namespace PARR.TemplateDistributor.Services
{
    internal class ValidatorService : IValidatorService
    {
        private readonly IServiceProvider serviceProvider;
        private readonly ILogger<ValidatorService> logger;

        public ValidatorService(IServiceProvider serviceProvider,
            ILogger<ValidatorService> logger
            )
        {
            this.serviceProvider = serviceProvider;
            this.logger = logger;
        }
        public async Task<bool> IsValidJobGroupAsync(Guid jobGroupId)
        {
            using (var scope = serviceProvider.CreateScope())
            {

                var service = scope.ServiceProvider.GetService<IJobGroupRepository>();

                if (service == null)
                    throw new Exception($"Не найден сервис: {nameof(IJobGroupRepository)}");

                var jobGroup = await service.Get().Include(t => t.DistributionConfig).FirstOrDefaultAsync(t => t.Id == jobGroupId);

                if (jobGroup == null)
                {
                    logger.LogError($"Не найдена группа работ с Id: {jobGroupId}", jobGroupId);
                    return false;
                }

                if (!jobGroup.IsAutoDistributionEnabled || jobGroup.DistributionConfig == null)
                {
                    logger.LogError("Для группы работ {jobGroupId} отсутствуют настройки автораспределения. " +
                        "IsAutoDistributionEnabled: {IsAutoDistributionEnabled}, есть настройки в таблице {DistributionConfig}, {existConfig}", jobGroupId, jobGroup.IsAutoDistributionEnabled, nameof(JobGroupDistributionConfig), jobGroup.DistributionConfig != null);
                    return false;
                }

                return true;
            }
        }
    }
}
