using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.Constants;
using PARR.DAL.Models;
using PARR.DAL.Models.Base;
using PARR.DAL.Models.Job;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Base;
using PARR.DAL.Services.Interfaces.Job;

namespace PARR.TemplateActivator;

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> IsValidObjectIdAsync(Guid id, SyncTaskEntityTypeEnum entityType)
    {
        switch (entityType)
        {
            case (SyncTaskEntityTypeEnum.JobGroup):
                return await IsValidAync<IJobGroupService, JobGroup>(id);

            case (SyncTaskEntityTypeEnum.Job):
                return await IsValidAync<IJobService, Job>(id);

            case (SyncTaskEntityTypeEnum.Template):
                return await IsValidAync<ITemplateService, Template>(id);
        }

        return false;
    }


    private async Task<bool> IsValidAync<TService, TEntity>(Guid id)
                                                where TService : class, IBaseService<TEntity>
                                                where TEntity : class, IBase
    {
        using (var scope = serviceProvider.CreateScope())
        {
            var service = scope.ServiceProvider.GetService<TService>();
            if (service == null)
                throw new Exception($"Не найден сервис: {typeof(TService).Name}");

            var obj = await service.GetAsync(id);

            if (obj == null)
            {
                logger.LogError($"Не объект {nameof(id)}: {id} в {typeof(TService).Name}");
                return false;
            }

            return true;
        }
    }

}