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

namespace ChatService.API.Application.Commands.Keys;

/// <summary>
/// EN: Handler for RotatePreKeyCommand.
/// VI: Handler cho RotatePreKeyCommand.
/// </summary>
public class RotatePreKeyCommandHandler : IRequestHandler<RotatePreKeyCommand, RotatePreKeyResult>
{
    private readonly IChatUserRepository _chatUserRepository;
    private readonly ILogger<RotatePreKeyCommandHandler> _logger;

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

    public async Task<RotatePreKeyResult> Handle(RotatePreKeyCommand request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Rotating pre-key for user {ChatUserId}", request.ChatUserId);

        var user = await _chatUserRepository.GetByIdAsync(request.ChatUserId, cancellationToken);
        
        if (user == null)
        {
            throw new InvalidOperationException($"Chat user {request.ChatUserId} not found");
        }

        user.RotateSignedPreKey(request.NewSignedPreKey, request.NewSignedPreKeySignature);

        _chatUserRepository.Update(user);
        await _chatUserRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation("Pre-key rotated for user {ChatUserId}", request.ChatUserId);

        return new RotatePreKeyResult(DateTime.UtcNow);
    }
}
