using Application.Abstractions.Messaging;
using Application.Abstractions.Cache;
using Application.Abstractions.Crypto;

namespace Application.Features.Api.Crypto.Candle.GetSeconds;

public sealed class Handler(IUpbitClient upbit, ICacheService cache) : IQueryHandler<Query, Response>
{
    private static readonly TimeSpan _cacheExpiry = TimeSpan.FromMinutes(1);

    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var count = Math.Clamp(request.Count, 1, 200);
        var cacheKey = CacheKeys.CryptoCandle(request.Market, "s");

        // 캐시 확인
        var cached = await cache.GetAsync<List<Response.CandleItem>>(cacheKey, ct);
        if (cached is { Count: > 0 })
        {
            return new Response(cached);
        }

        // Upbit REST API 호출
        var candles = await upbit.GetSecondCandlesAsync(request.Market, count, ct);

        var items = candles
            .OrderBy(c => c.CandleDateTimeUtc)
            .Select(c => new Response.CandleItem(
                c.CandleDateTimeUtc,
                c.CandleDateTimeKst,
                c.OpeningPrice,
                c.HighPrice,
                c.LowPrice,
                c.TradePrice,
                c.Timestamp,
                c.CandleAccTradePrice,
                c.CandleAccTradeVolume
            ))
            .ToList();

        // Redis 캐시 저장 (1분 — 초봉은 짧게)
        if (items.Count > 0)
        {
            await cache.SetAsync(cacheKey, items, _cacheExpiry, ct);
        }

        return new Response(items);
    }
}