using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using QuantEngine.Core.Interfaces;
using QuantEngine.Infrastructure.Data;

namespace QuantEngine.Infrastructure.Repositories;

public class PriceHistoryReader : IPriceHistoryReader
{
    private readonly IDbConnectionFactory _connectionFactory;

    public PriceHistoryReader(IDbConnectionFactory connectionFactory)
    {
        _connectionFactory = connectionFactory;
    }

    public async Task<List<PriceHistoryDailyRecord>> GetBarsAsOf(string ticker, DateOnly asOfDate, int lookback)
    {
        using var conn = _connectionFactory.CreateConnection();
        var rows = await conn.QueryAsync<PriceHistoryDailyRecordRow>(@"
            SELECT ticker, trade_date, open, high, low, close, volume, source, provenance
            FROM quantengine.price_history_daily
            WHERE ticker = @Ticker AND trade_date <= @AsOfDate
            ORDER BY trade_date DESC
            LIMIT @Lookback",
            new { Ticker = ticker, AsOfDate = asOfDate, Lookback = lookback });

        return rows.Select(r => new PriceHistoryDailyRecord(
            r.Ticker,
            r.TradeDate,
            r.Open,
            r.High,
            r.Low,
            r.Close,
            r.Volume,
            r.Source,
            r.Provenance)).ToList();
    }

    private record PriceHistoryDailyRecordRow(
        string Ticker,
        DateOnly TradeDate,
        decimal Open,
        decimal High,
        decimal Low,
        decimal Close,
        long Volume,
        string Source,
        string? Provenance);
}
