using Tiku.Application.Jobs;

namespace Tiku.Infrastructure.Jobs;

internal sealed class BackgroundJobHandlerRegistry
{
    private readonly IReadOnlyDictionary<string, IBackgroundJobHandler> handlers;

    public BackgroundJobHandlerRegistry(IEnumerable<IBackgroundJobHandler> handlers)
    {
        var registered = new Dictionary<string, IBackgroundJobHandler>(StringComparer.Ordinal);
        foreach (var handler in handlers)
        {
            var jobType = handler.JobType.Trim().ToLowerInvariant();
            if (!registered.TryAdd(jobType, handler))
                throw new InvalidOperationException($"Duplicate background job handler for '{jobType}'.");
        }

        this.handlers = registered;
    }

    public IBackgroundJobHandler GetRequired(string jobType)
    {
        var normalized = jobType.Trim().ToLowerInvariant();
        return handlers.TryGetValue(normalized, out var handler)
            ? handler
            : throw new InvalidOperationException($"Unsupported background job type '{normalized}'.");
    }
}
