using Application.Abstractions.Crypto;
using Microsoft.AspNetCore.SignalR;

namespace Web.Api.Hubs;

public sealed class CryptoHubService(
    IHubContext<CryptoHub, ICryptoHubClient> hubContext
) : ICryptoHubService
{
    public async Task SendTickerAsync(CryptoHubData.TickerData ticker, CancellationToken ct)
    {
        await hubContext.Clients.Group($"ticker:{ticker.Market.ToLower()}").ReceiveTicker(ticker);
    }

    public async Task SendTickersAsync(IReadOnlyList<CryptoHubData.TickerData> tickers, CancellationToken ct)
    {
        if (tickers.Count == 0)
        {
            return;
        }

        var quote = tickers[0].Market.Split('-')[0].ToLower();

        await hubContext.Clients.Group($"tickers:{quote}").ReceiveTickers(tickers);
        await hubContext.Clients.Group("tickers").ReceiveTickers(tickers);
    }

    public async Task SendTradeAsync(CryptoHubData.TradeData trade, CancellationToken ct)
    {
        await hubContext.Clients.Group($"trade:{trade.Market.ToLower()}").ReceiveTrade(trade);
    }

    public async Task SendOrderbookAsync(CryptoHubData.OrderbookData orderbook, CancellationToken ct)
    {
        await hubContext.Clients.Group($"orderbook:{orderbook.Market.ToLower()}").ReceiveOrderbook(orderbook);
    }

    public async Task SendCandleAsync(CryptoHubData.CandleData candle, CancellationToken ct)
    {
        await hubContext.Clients.Group($"candle:{candle.Market.ToLower()}").ReceiveCandle(candle);
    }
}