using MediatR;
using MembershipService.Domain.AggregatesModel.ExperienceAggregate;

namespace MembershipService.API.Application.Queries;

/// <summary>
/// EN: Handler for getting experience history.
/// VI: Handler để lấy lịch sử EXP.
/// </summary>
public class GetExperienceHistoryQueryHandler : IRequestHandler<GetExperienceHistoryQuery, ExperienceHistoryResult>
{
    private readonly IExperienceTransactionRepository _experienceTransactionRepository;

    public GetExperienceHistoryQueryHandler(IExperienceTransactionRepository experienceTransactionRepository)
    {
        _experienceTransactionRepository = experienceTransactionRepository 
            ?? throw new ArgumentNullException(nameof(experienceTransactionRepository));
    }

    public async Task<ExperienceHistoryResult> Handle(GetExperienceHistoryQuery request, CancellationToken cancellationToken)
    {
        var skip = request.PageIndex * request.PageSize;
        
        var transactions = await _experienceTransactionRepository.GetByMemberIdAsync(
            request.MemberId, 
            skip, 
            request.PageSize);

        var totalCount = await _experienceTransactionRepository.GetCountByMemberIdAsync(request.MemberId);

        var transactionDtos = transactions.Select(t => new ExperienceTransactionDto
        {
            Id = t.Id,
            Points = t.Points,
            Source = t.Source?.Name ?? "Unknown",
            SourceId = t.SourceId,
            ReferenceId = t.ReferenceId,
            LevelAtTime = t.LevelAtTime,
            CreatedAt = t.CreatedAt
        });

        return new ExperienceHistoryResult
        {
            Transactions = transactionDtos,
            TotalCount = totalCount,
            PageIndex = request.PageIndex,
            PageSize = request.PageSize
        };
    }
}
