using Microsoft.Extensions.DependencyInjection;
using PARR.Domain.Enums;

namespace PARR.Core.Services.TaskServices.Handlers.Factory
{
    public class TaskHandlerFactory : ITaskHandlerFactory
    {
        private readonly IServiceProvider serviceProvider;
        private readonly Dictionary<TaskTypeEnum, Type> handlers;

        public TaskHandlerFactory(IServiceProvider serviceProvider, IEnumerable<BaseTaskHandler> handlers)
        {
            this.serviceProvider = serviceProvider;
            this.handlers = handlers.ToDictionary(t => t.SupportedType, t => t.GetType());
        }

        public BaseTaskHandler GetHandler(TaskTypeEnum taskType)
        {
            if (!handlers.TryGetValue(taskType, out var handlerType))
            {
                throw new InvalidOperationException($"Не зарегистрирован обработчик для типа {taskType}");
            }

            return (BaseTaskHandler)serviceProvider.GetRequiredService(handlerType);
        }

        public IEnumerable<TaskTypeEnum> GetSupportedTypes()
        {
            return handlers.Keys;
        }

    }
}
