using System.Threading.Channels;
using Femto.Common.Integration;

namespace Femto.Api.Infrastructure;

public class EventBus(Channel<IEvent> channel) : BackgroundService, IEventBus
{
    private readonly ICollection<IEventBus.Subscriber> _subscribers = [];

    public Task Publish<T>(T evt)
        where T : IEvent
    {
        channel.Writer.TryWrite(evt);
        
        return Task.CompletedTask;
    }

    public void Subscribe(IEventBus.Subscriber subscriber)
    {
        this._subscribers.Add(subscriber);
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await foreach (var message in channel.Reader.ReadAllAsync(stoppingToken))
        {
            await Task.WhenAll(
                this._subscribers.Select(subscriber => subscriber.Invoke(message, stoppingToken))
            );
        }
    }
}
