using MediatR;
using ChatService.Domain.AggregatesModel.UserAggregate;

namespace ChatService.API.Application.Queries.Keys;

/// <summary>
/// EN: Handler for GetMyKeyBundleQuery.
/// VI: Handler cho GetMyKeyBundleQuery.
/// </summary>
public class GetMyKeyBundleQueryHandler : IRequestHandler<GetMyKeyBundleQuery, MyKeyBundleDto?>
{
    private readonly IChatUserRepository _chatUserRepository;
    private readonly ILogger<GetMyKeyBundleQueryHandler> _logger;

    public GetMyKeyBundleQueryHandler(
        IChatUserRepository chatUserRepository,
        ILogger<GetMyKeyBundleQueryHandler> logger)
    {
        _chatUserRepository = chatUserRepository;
        _logger = logger;
    }

    public async Task<MyKeyBundleDto?> Handle(GetMyKeyBundleQuery request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Getting my key bundle for {IdentityUserId}", request.IdentityUserId);

        var user = await _chatUserRepository.GetByIdentityUserIdAsync(request.IdentityUserId, cancellationToken);
        
        if (user == null)
        {
            _logger.LogInformation("Chat user not found for {IdentityUserId}", request.IdentityUserId);
            return null;
        }

        var availableKeys = await _chatUserRepository.GetAvailablePreKeyCountAsync(user.Id, cancellationToken);

        return new MyKeyBundleDto(
            user.Id,
            user.KeyBundle != null,
            user.KeyBundle?.SignedPreKeyTimestamp,
            user.KeyBundle?.NeedsRotation() ?? true,
            availableKeys
        );
    }
}
