using SIGCM2.Application.Abstractions;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Common;

namespace SIGCM2.Application.Products.List;

public sealed class ListProductsQueryHandler
    : ICommandHandler<ListProductsQuery, PagedResult<ProductListItemDto>>
{
    private readonly IProductRepository _repo;

    public ListProductsQueryHandler(IProductRepository repo)
    {
        _repo = repo;
    }

    public async Task<PagedResult<ProductListItemDto>> Handle(ListProductsQuery query)
    {
        var page = Math.Max(1, query.Page);
        var pageSize = Math.Clamp(query.PageSize, 1, 100);

        var repoQuery = new ProductsQuery(
            page, pageSize, query.Activo, query.Search,
            query.MedioId, query.ProductTypeId, query.RubroId);
        var paged = await _repo.GetPagedAsync(repoQuery);

        var items = paged.Items.Select(p => new ProductListItemDto(
            p.Id, p.Nombre,
            p.MedioId, p.ProductTypeId, p.RubroId,
            p.BasePrice, p.PriceDurationDays,
            p.IsActive)).ToList();

        return new PagedResult<ProductListItemDto>(items, paged.Page, paged.PageSize, paged.Total);
    }
}
