using Microsoft.Extensions.Logging;
using ProjectShoeShop.Repositories;
using ProjectShoeShop.Repositories.Implementations;

namespace ProjectShoeShop.Reports;

internal class ChartReport
{
    private readonly IOrderRepository _orderRepository;
    private readonly IShoesRepository _shoesRepository;
    private readonly ILogger<ChartReport> _logger;

    public ChartReport(IOrderRepository orderRepository, IShoesRepository shoesRepository, ILogger<ChartReport> logger)
    {
        _orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
        _shoesRepository = shoesRepository ?? throw new ArgumentNullException(nameof(shoesRepository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public bool CreateChart(string filePath, DateTime dateTime)
    {
        try
        {
            new PdfBuilder(filePath)
                .AddHeader("Продажи обуви")
                .AddPieChart("Обувь", GetData(dateTime))
                .Build();
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Ошибка при формировании документа");
            return false;
        }
    }
    private List<(string Caption, double Value)> GetData(DateTime dateTime)
    {
        var fuelNames = _shoesRepository.ReadShoes()
            .ToDictionary(f => f.Id, f => f.Name);

        return _orderRepository
            .ReadOrder()
            .Where(x => x.OrderDate.Date == dateTime.Date)
            .SelectMany(x => x.OrderItems)
            .GroupBy(x => x.ShoesId)
            .Select(g => (Caption: fuelNames[g.Key].ToString(), Value: (double)g.Sum(x => x.NumberOfPairs)))
            .ToList();
    }
}
