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

namespace MembershipService.API.Application.Commands;

/// <summary>
/// EN: Handler for updating member profile.
/// VI: Handler để cập nhật profile member.
/// </summary>
public class UpdateMemberProfileCommandHandler : IRequestHandler<UpdateMemberProfileCommand, UpdateMemberProfileResult>
{
    private readonly IMemberRepository _memberRepository;
    private readonly ILogger<UpdateMemberProfileCommandHandler> _logger;

    public UpdateMemberProfileCommandHandler(
        IMemberRepository memberRepository,
        ILogger<UpdateMemberProfileCommandHandler> logger)
    {
        _memberRepository = memberRepository ?? throw new ArgumentNullException(nameof(memberRepository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<UpdateMemberProfileResult> Handle(UpdateMemberProfileCommand request, CancellationToken cancellationToken)
    {
        var member = await _memberRepository.GetByIdAsync(request.MemberId, cancellationToken);
        if (member == null)
        {
            throw new KeyNotFoundException($"Member {request.MemberId} not found");
        }

        // EN: Update gender if provided
        // VI: Cập nhật gender nếu được cung cấp
        if (request.Gender != null)
        {
            member.UpdateGender(request.Gender);
        }

        // EN: Update country code if provided
        // VI: Cập nhật country code nếu được cung cấp
        if (!string.IsNullOrWhiteSpace(request.CountryCode))
        {
            member.UpdateCountryCode(request.CountryCode);
        }

        // EN: Update preferences if provided
        // VI: Cập nhật preferences nếu được cung cấp
        if (request.Preferences != null)
        {
            member.UpdatePreferences(request.Preferences);
        }

        _memberRepository.Update(member);
        await _memberRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation("Updated profile for member {MemberId}", request.MemberId);

        return new UpdateMemberProfileResult
        {
            MemberId = member.Id,
            Success = true,
            UpdatedAt = member.UpdatedAt
        };
    }
}
