using System.Text.Json;
using MediatR;
using MembershipService.Domain.AggregatesModel.MemberAggregate;

namespace MembershipService.API.Application.Queries;

/// <summary>
/// EN: Handler for getting paginated list of members.
/// VI: Handler để lấy danh sách members phân trang.
/// </summary>
public class GetMembersQueryHandler : IRequestHandler<GetMembersQuery, GetMembersResult>
{
    private readonly IMemberRepository _memberRepository;

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

    public async Task<GetMembersResult> Handle(GetMembersQuery request, CancellationToken cancellationToken)
    {
        var (members, totalCount) = await _memberRepository.GetPaginatedAsync(
            request.PageIndex,
            request.PageSize,
            request.SearchTerm,
            cancellationToken);

        var memberDtos = members.Select(m =>
        {
            string? displayName = null, phone = null;
            if (!string.IsNullOrWhiteSpace(m.Preferences))
            {
                try
                {
                    var prefs = JsonSerializer.Deserialize<JsonElement>(m.Preferences);
                    if (prefs.TryGetProperty("name", out var n)) displayName = n.GetString();
                    if (prefs.TryGetProperty("phone", out var p)) phone = p.GetString();
                }
                catch { }
            }
            return new MemberDto
            {
                Id = m.Id,
                UserId = m.UserId,
                Gender = m.Gender,
                CountryCode = m.CountryCode,
                Preferences = m.Preferences,
                DisplayName = displayName,
                Phone = phone,
                CurrentLevel = m.CurrentLevel,
                CurrentExp = m.CurrentExp,
                TotalExpEarned = m.TotalExpEarned,
                CreatedAt = m.CreatedAt,
                UpdatedAt = m.UpdatedAt
            };
        });

        return new GetMembersResult
        {
            Members = memberDtos,
            TotalCount = totalCount,
            PageIndex = request.PageIndex,
            PageSize = request.PageSize
        };
    }
}
