using MediatR;
using Knot.Contracts.Conversations.Domain;
using Knot.Shared.Kernel;
using Knot.Contracts.Conversations.Application.Abstractions;

namespace Knot.Modules.Conversations.Application.Messages.Read;

public sealed record ReadMessagesCommand(Guid ChatId, Guid UserId, Guid LastReadMessageId, long LastReadSequenceId) : ICommand;

public sealed class ReadMessagesCommandHandler : ICommandHandler<ReadMessagesCommand>
{
    private readonly IChatRepository _chatRepository;
    private readonly IChatsUnitOfWork _unitOfWork;

    public ReadMessagesCommandHandler(IChatRepository chatRepository, IChatsUnitOfWork unitOfWork)
    {
        _chatRepository = chatRepository;
        _unitOfWork = unitOfWork;
    }

    public async Task<Result> Handle(ReadMessagesCommand request, CancellationToken cancellationToken)
    {
        var chat = await _chatRepository.GetByIdAsync(request.ChatId, cancellationToken);
        if (chat == null) return Result.Failure(ChatErrors.NotFound);

        var member = chat.Members.FirstOrDefault(m => m.UserId == request.UserId);
        if (member == null) return Result.Failure(ChatErrors.NotMember);

        member.UpdateReadCursor(request.LastReadMessageId, request.LastReadSequenceId);

        await _unitOfWork.SaveChangesAsync(cancellationToken);

        return Result.Success();
    }
}

