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

namespace SIGCM2.Application.ProductTypes.List;

public sealed class ListProductTypesQueryHandler
    : ICommandHandler<ListProductTypesQuery, PagedResult<ProductTypeListItemDto>>
{
    private readonly IProductTypeRepository _repo;

    public ListProductTypesQueryHandler(IProductTypeRepository repo)
    {
        _repo = repo;
    }

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

        var repoQuery = new ProductTypesQuery(page, pageSize, query.Activo, query.Search);
        var paged = await _repo.GetPagedAsync(repoQuery);

        var items = paged.Items.Select(p => new ProductTypeListItemDto(
            p.Id, p.Nombre,
            p.HasDuration, p.RequiresText, p.RequiresCategory, p.IsBundle,
            p.AllowImages, p.IsActive)).ToList();

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