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

namespace SIGCM2.Application.Rubros.GetTree;

public sealed class GetRubroTreeQueryHandler : ICommandHandler<GetRubroTreeQuery, IReadOnlyList<RubroTreeNodeDto>>
{
    private readonly IRubroRepository _repo;
    private readonly IAvisoQueryRepository _avisoQuery;

    public GetRubroTreeQueryHandler(IRubroRepository repo, IAvisoQueryRepository avisoQuery)
    {
        _repo = repo;
        _avisoQuery = avisoQuery;
    }

    public async Task<IReadOnlyList<RubroTreeNodeDto>> Handle(GetRubroTreeQuery query)
    {
        var all = await _repo.GetAllAsync(query.IncluirInactivos);
        var ids = all.Select(r => r.Id).ToList();
        // CAT-002: single batch call — avoids N+1 when PRD-002 activates the real implementation
        var avisoCounts = await _avisoQuery.CountAvisosBatchAsync(ids);
        return RubroTreeBuilder.Build(all, query.IncluirInactivos, avisoCounts);
    }
}
