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

namespace SIGCM2.Application.TiposDeIva.List;

public sealed class ListTiposDeIvaQueryHandler
    : ICommandHandler<ListTiposDeIvaQuery, PagedResult<TipoDeIvaDto>>
{
    private readonly ITipoDeIvaRepository _repo;

    public ListTiposDeIvaQueryHandler(ITipoDeIvaRepository repo)
    {
        _repo = repo;
    }

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

        var repoQuery = new TiposDeIvaQuery(page, pageSize, query.Activo, query.Codigo);
        var paged = await _repo.ListAsync(repoQuery);

        var items = paged.Items.Select(TipoDeIvaMapper.ToDto).ToList();

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