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

namespace SIGCM2.Application.IngresosBrutos.List;

public sealed class ListIngresosBrutosQueryHandler
    : ICommandHandler<ListIngresosBrutosQuery, PagedResult<IngresosBrutosDto>>
{
    private readonly IIngresosBrutosRepository _repo;

    public ListIngresosBrutosQueryHandler(IIngresosBrutosRepository repo)
    {
        _repo = repo;
    }

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

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

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

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