package com.atlassian.bitbucket.mesh.request;

import com.atlassian.bitbucket.mesh.rpc.v1.RpcCommit;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcGetCommitResponse;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.Status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

@RunWith(MockitoJUnitRunner.class)
public class RequestServerCallTest {

    @InjectMocks
    private RequestServerCall<Object, Object> call;
    @Mock
    private ServerCall<Object, Object> delegate;
    @Mock
    private GrpcRequestDescriptor descriptor;

    @Test
    public void testClose() {
        Status status = Status.UNKNOWN;
        Metadata trailers = new Metadata();

        call.close(status, trailers);

        verify(delegate).close(same(status), same(trailers)); //Status.equals throws an exception, so no eq
        verify(descriptor).onClose(same(status));
    }

    @Test
    public void testOnMessage() {
        RpcGetCommitResponse response = RpcGetCommitResponse.newBuilder()
                .setCommit(RpcCommit.newBuilder()
                        .setId("ba34d26579a1074902b0ef1029d3348fcbf7019a")
                        .build())
                .build();

        call.sendMessage(response);

        verify(delegate).sendMessage(same(response));
        verify(descriptor).onMessageSent();
        verify(descriptor).onBytesSent(eq((long) response.getSerializedSize()));
        verifyNoMoreInteractions(delegate, descriptor);
    }

    @Test
    public void testOnMessageHandlesNonMessages() {
        call.sendMessage("Test");

        verify(delegate).sendMessage(eq("Test"));
        verify(descriptor).onMessageSent();
        verifyNoMoreInteractions(delegate, descriptor);
    }
}
