using MediatR;
using MembershipService.Domain.AggregatesModel.MemberAggregate;

namespace MembershipService.API.Application.Queries;

/// <summary>
/// EN: Handler for getting member by ID.
/// VI: Handler để lấy member theo ID.
/// </summary>
public class GetMemberByIdQueryHandler : IRequestHandler<GetMemberByIdQuery, MemberDto?>
{
    private readonly IMemberRepository _memberRepository;

    public GetMemberByIdQueryHandler(IMemberRepository memberRepository)
    {
        _memberRepository = memberRepository ?? throw new ArgumentNullException(nameof(memberRepository));
    }

    public async Task<MemberDto?> Handle(GetMemberByIdQuery request, CancellationToken cancellationToken)
    {
        var member = await _memberRepository.GetByIdAsync(request.MemberId, cancellationToken);
        if (member == null)
        {
            return null;
        }

        return MapToDto(member);
    }

    private static MemberDto MapToDto(Member member)
    {
        return new MemberDto
        {
            Id = member.Id,
            UserId = member.UserId,
            Gender = member.Gender,
            CountryCode = member.CountryCode,
            Preferences = member.Preferences,
            CurrentLevel = member.CurrentLevel,
            CurrentExp = member.CurrentExp,
            TotalExpEarned = member.TotalExpEarned,
            CreatedAt = member.CreatedAt,
            UpdatedAt = member.UpdatedAt
        };
    }
}
