using System;
using System.Threading;
using System.Threading.Tasks;
using Knot.Shared.Kernel;
using Knot.Contracts.Conversations.Domain;
using Knot.Contracts.Conversations.Application.Abstractions;
using MediatR;
using System.Linq;

namespace Knot.Modules.Conversations.Application.Chats.Clear;

public record ClearChatCommand(Guid ChatId, Guid UserId) : ICommand<MessageResponse>;

internal sealed class ClearChatCommandHandler : ICommandHandler<ClearChatCommand, MessageResponse>
{
    private readonly IChatRepository _chatRepository;

    public ClearChatCommandHandler(IChatRepository chatRepository)
    {
        _chatRepository = chatRepository;
    }

    public async Task<Result<MessageResponse>> Handle(ClearChatCommand request, CancellationToken cancellationToken)
    {
        var chat = await _chatRepository.GetByIdAsync(request.ChatId, cancellationToken);
        if (chat == null || !chat.Members.Any(m => m.UserId == request.UserId))
        {
            return Result.Failure<MessageResponse>(ChatErrors.ChatNotFound);
        }

        // Currently a placeholder
        return Result.Success(new MessageResponse("Cleared"));
    }
}

