using SIGCM2.Application.Abstractions;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Products.Prices;
using SIGCM2.Domain.Exceptions;

namespace SIGCM2.Application.Products.Prices.GetHistory;

/// <summary>
/// PRD-003 — Handler de GetProductPricesQuery.
/// Verifica que el producto exista (404 si no), luego retorna historial de precios
/// ordenado descending por PriceValidFrom (responsabilidad del repo — SQL ORDER BY).
/// Lista vacía es válida (nuevo producto sin precios registrados aún).
/// </summary>
public sealed class GetProductPricesQueryHandler
    : ICommandHandler<GetProductPricesQuery, IReadOnlyList<ProductPriceDto>>
{
    private readonly IProductPriceRepository _pricesRepo;
    private readonly IProductRepository _productsRepo;

    public GetProductPricesQueryHandler(
        IProductPriceRepository pricesRepo,
        IProductRepository productsRepo)
    {
        _pricesRepo = pricesRepo;
        _productsRepo = productsRepo;
    }

    public async Task<IReadOnlyList<ProductPriceDto>> Handle(GetProductPricesQuery query)
    {
        // Verifica existencia del producto (lanza 404 si no existe).
        _ = await _productsRepo.GetByIdAsync(query.ProductId)
            ?? throw new ProductNotFoundException(query.ProductId);

        var prices = await _pricesRepo.GetByProductIdAsync(query.ProductId);

        return prices
            .Select(p => new ProductPriceDto(
                p.Id, p.ProductId, p.Price,
                p.PriceValidFrom, p.PriceValidTo, p.IsActive))
            .ToList();
    }
}
