using Managing.Application.Abstractions.Repositories;
using Managing.Application.Abstractions.Services;
using Managing.Domain.Accounts;
using Managing.Domain.Candles;
using Microsoft.Extensions.Logging;
using static Managing.Common.Enums;

namespace Managing.Application.Trading;

public class PricesService : IPricesService
{
    private readonly ILogger<PricesService> _logger;
    private readonly IExchangeService _exchangeService;
    private readonly IAccountService _accountService;
    private readonly ICandleRepository _candleRepository;

    public PricesService(
        ILogger<PricesService> logger,
        IExchangeService exchangeService,
        ICandleRepository candleRepository,
        IAccountService accountService)
    {
        _logger = logger;
        _exchangeService = exchangeService;
        _candleRepository = candleRepository;
        _accountService = accountService;
    }

    public async Task UpdatePrice(TradingExchanges exchange, Ticker ticker, Timeframe timeframe)
    {
        try
        {
            var account = new Account()
            {
                Exchange = exchange,
            };

            if (account == null)
                throw new Exception($"Enable to found account for exchange {exchange}");

            var lastCandles =
                await _candleRepository.GetCandles(exchange, ticker, timeframe, DateTime.UtcNow.AddDays(-2));
            var lastCandle = lastCandles.LastOrDefault();
            var startDate = lastCandle != null ? lastCandle.Date : new DateTime(2017, 1, 1);

            List<Candle> newCandles;
            if (!lastCandles.Any())
            {
                newCandles = await _exchangeService.GetCandles(account, ticker, startDate, timeframe, true);
            }
            else
            {
                newCandles = await _exchangeService.GetCandles(account, ticker, startDate, timeframe, false);
            }

            var candles = !lastCandles.Any() ? newCandles : newCandles.Where(c => c.Date > lastCandle?.Date);
            var candlesInserted = 0;

            foreach (var newCandle in candles)
            {
                if (lastCandle == null || newCandle.Date > lastCandle.Date)
                {
                    _candleRepository.InsertCandle(newCandle);
                    candlesInserted++;
                }
            }

            if (candlesInserted > 0)
                _logger.LogInformation($"[{exchange}][{ticker}][{timeframe}] New candles inserted : {candlesInserted}");
        }
        catch (Exception ex)
        {
            SentrySdk.CaptureException(ex);
            _logger.LogError($"[{exchange}][{ticker}][{timeframe}] Error : {ex.Message} |  {ex.StackTrace}");
        }
    }
}