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

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<IJobGroupRepository, JobGroup>(id);

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

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

        return false;
    }


    private async Task<bool> IsValidAync<TService, TEntity>(Guid id)
                                                where TService : class, IBaseRepository<TEntity>
                                                where TEntity : class, IBaseEntity
    {
        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;
        }
    }

}