using System.Threading.Channels;
using Microsoft.Extensions.Logging;
using SatelliteProvider.Common.DTO;
using SatelliteProvider.Common.Interfaces;

namespace SatelliteProvider.Services.RegionProcessing;

public class RegionRequestQueue : IRegionRequestQueue
{
    private readonly Channel<RegionRequest> _queue;
    private readonly ILogger<RegionRequestQueue>? _logger;

    public RegionRequestQueue(int capacity, ILogger<RegionRequestQueue>? logger = null)
    {
        var options = new BoundedChannelOptions(capacity)
        {
            FullMode = BoundedChannelFullMode.Wait
        };
        _queue = Channel.CreateBounded<RegionRequest>(options);
        _logger = logger;
        _logger?.LogInformation("RegionRequestQueue created with capacity {Capacity}", capacity);
    }

    public async ValueTask EnqueueAsync(RegionRequest request, CancellationToken cancellationToken = default)
    {
        await _queue.Writer.WriteAsync(request, cancellationToken);
    }

    public async ValueTask<RegionRequest?> DequeueAsync(CancellationToken cancellationToken = default)
    {
        if (await _queue.Reader.WaitToReadAsync(cancellationToken))
        {
            if (_queue.Reader.TryRead(out var request))
            {
                return request;
            }
        }
        return null;
    }

    public int Count => _queue.Reader.Count;
}

