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

namespace SIGCM2.Application.Medios.List;

public sealed class ListMediosQueryHandler : ICommandHandler<ListMediosQuery, PagedResult<MedioListItemDto>>
{
    private readonly IMedioRepository _repo;

    public ListMediosQueryHandler(IMedioRepository repo)
    {
        _repo = repo;
    }

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

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

        var items = paged.Items
            .Select(m => new MedioListItemDto(m.Id, m.Codigo, m.Nombre, m.Tipo, m.PlataformaEmpresaId, m.Activo))
            .ToList();

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