package io.trustbuilder.mfa.android.demoapp.utils;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.messaging.FirebaseMessaging;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;

@RunWith(RobolectricTestRunner.class)
public class FirebaseServiceImplTest {

    @Mock
    FirebaseMessaging firebaseMessaging;

    @Mock
    Task<String> mockTask;

    private FirebaseServiceImpl service;

    @Before
    public void setUp() {
        MockitoAnnotations.openMocks(this);
        service = new FirebaseServiceImpl(firebaseMessaging);
    }

    @Test
    public void fetchToken_success() {
        when(firebaseMessaging.getToken()).thenReturn(mockTask);

        doAnswer(invocation -> {
            OnCompleteListener<String> listener = invocation.getArgument(0);
            when(mockTask.isSuccessful()).thenReturn(true);
            when(mockTask.getResult()).thenReturn("mockToken");
            listener.onComplete(mockTask);
            return null;
        }).when(mockTask).addOnCompleteListener(any(OnCompleteListener.class));

        FirebaseService.FirebaseCallback callback = mock(FirebaseService.FirebaseCallback.class);
        service.fetchToken(callback);

        verify(callback).onTokenReceived("mockToken");
        verify(callback, never()).onError(any());
    }

    @Test
    public void fetchToken_fail() {
        when(firebaseMessaging.getToken()).thenReturn(mockTask);

        doAnswer(invocation -> {
            OnCompleteListener<String> listener = invocation.getArgument(0);
            when(mockTask.isSuccessful()).thenReturn(false);
            when(mockTask.getException()).thenReturn(new RuntimeException("Failed"));
            listener.onComplete(mockTask);
            return null;
        }).when(mockTask).addOnCompleteListener(any(OnCompleteListener.class));

        FirebaseService.FirebaseCallback callback = mock(FirebaseService.FirebaseCallback.class);
        service.fetchToken(callback);

        verify(callback).onError(any(RuntimeException.class));
        verify(callback, never()).onTokenReceived(any());
    }
}