using Application.Abstractions.Messaging;
using Web.Api.Common;

namespace Web.Api.Endpoints.Crypto;

internal sealed class CryptoTrades : IEndpoint
{
    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        app.MapGet("api/crypto/{market}/trades", async (
            string market,
            int? count,
            ISender sender,
            CancellationToken ct
        ) =>
        {
            var response = await sender.Send(new Application.Features.Api.Crypto.Trade.GetRecent.Query(NormalizeMarket(market), count ?? 50), ct);
            return ApiResponse.Ok(response.Trades);
        })
        .WithTags("Crypto")
        .AllowAnonymous();

        app.MapGet("api/crypto/{market}/trades/live", async (
            string market,
            ISender sender,
            CancellationToken ct
        ) =>
        {
            var response = await sender.Send(new Application.Features.Api.Crypto.Trade.GetLive.Query(NormalizeMarket(market)), ct);
            return ApiResponse.Ok(response.Trade);
        })
        .WithTags("Crypto")
        .AllowAnonymous();
    }

    private static string NormalizeMarket(string input) =>
        input.Contains('-') ? input.ToUpper() : $"KRW-{input.ToUpper()}";
}