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 Knot.Modules.Conversations.Application.DTOs;
using MediatR;
using System.Linq;

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

public record TogglePinCommand(Guid ChatId, Guid UserId) : ICommand<TogglePinResponse>;

internal sealed class TogglePinCommandHandler : ICommandHandler<TogglePinCommand, TogglePinResponse>
{
    private readonly IChatRepository _chatRepository;
    private readonly IChatsUnitOfWork _uow;

    public TogglePinCommandHandler(IChatRepository chatRepository, IChatsUnitOfWork uow)
    {
        _chatRepository = chatRepository;
        _uow = uow;
    }

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

        var member = chat.Members.FirstOrDefault(m => m.UserId == request.UserId);
        if (member == null)
        {
            return Result.Failure<TogglePinResponse>(ChatErrors.ChatNotFound);
        }

        member.TogglePin();
        _chatRepository.Update(chat);
        await _uow.SaveChangesAsync(cancellationToken);

        return Result.Success(new TogglePinResponse(member.IsPinned));
    }
}

