using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using NSubstitute;
using Xunit;
using Knot.Shared.Kernel;
using Knot.Modules.Conversations.Domain;
using Knot.Modules.Messaging.Domain;
using Knot.Modules.Conversations.Application.Abstractions;
using Knot.Modules.Conversations.Application.Chats.Create;

namespace Knot.Modules.Conversations.UnitTests.Chats;

public class CreateChatCommandHandlerTests
{
    private readonly IChatRepository _chatRepository;
    private readonly IChatsUnitOfWork _unitOfWork;
    private readonly CreateChatCommandHandler _handler;

    public CreateChatCommandHandlerTests()
    {
        _chatRepository = Substitute.For<IChatRepository>();
        _unitOfWork = Substitute.For<IChatsUnitOfWork>();
        _handler = new CreateChatCommandHandler(_chatRepository, _unitOfWork);
    }

    [Fact]
    public async Task Handle_ShouldCreateChatAndAddMembers()
    {
        // Arrange
        var request = new CreateChatCommand("Test Group", ChatType.Group, new List<Guid> { Guid.NewGuid(), Guid.NewGuid() });

        // Act
        var result = await _handler.Handle(request, CancellationToken.None);

        // Assert
        result.IsSuccess.Should().BeTrue();
        result.Value.Should().NotBeEmpty();

        _chatRepository.Received(1).Add(Arg.Is<Chat>(c =>
            c.Name == "Test Group" &&
            c.Type == ChatType.Group &&
            c.Members.Count == 2 &&
            c.Members.First().Role == ChatRole.Owner &&
            c.Members.Last().Role == ChatRole.Member));

        await _unitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
    }
}


