using MediatR;
using MembershipService.Domain.AggregatesModel.LevelAggregate;

namespace MembershipService.API.Application.Queries;

/// <summary>
/// EN: Handler for getting level definitions.
/// VI: Handler để lấy level definitions.
/// </summary>
public class GetLevelDefinitionsQueryHandler : IRequestHandler<GetLevelDefinitionsQuery, IEnumerable<LevelDefinitionDto>>
{
    private readonly ILevelDefinitionRepository _levelDefinitionRepository;

    public GetLevelDefinitionsQueryHandler(ILevelDefinitionRepository levelDefinitionRepository)
    {
        _levelDefinitionRepository = levelDefinitionRepository 
            ?? throw new ArgumentNullException(nameof(levelDefinitionRepository));
    }

    public async Task<IEnumerable<LevelDefinitionDto>> Handle(GetLevelDefinitionsQuery request, CancellationToken cancellationToken)
    {
        var levels = request.IncludeInactive
            ? await _levelDefinitionRepository.GetAllAsync()
            : await _levelDefinitionRepository.GetAllActiveAsync();

        return levels.Select(l => new LevelDefinitionDto
        {
            Id = l.Id,
            LevelNumber = l.LevelNumber,
            Name = l.Name,
            RequiredExp = l.RequiredExp,
            Description = l.Description,
            IconUrl = l.IconUrl,
            BadgeColor = l.BadgeColor,
            IsActive = l.IsActive,
            Benefits = l.Benefits.Select(b => new LevelBenefitDto
            {
                Id = b.Id,
                BenefitType = b.BenefitType,
                BenefitValue = b.BenefitValue,
                Description = b.Description,
                IsActive = b.IsActive
            })
        });
    }
}
