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

import android.util.Log;

import com.google.firebase.messaging.FirebaseMessaging;

public class FirebaseServiceImpl implements FirebaseService {

    private static final String TAG = "FirebaseService";
    private final FirebaseMessaging firebaseMessaging;

    public FirebaseServiceImpl(FirebaseMessaging firebaseMessaging) {
        this.firebaseMessaging = firebaseMessaging;
    }

    @Override
    public void fetchToken(FirebaseCallback callback) {
        if (callback == null) {
            throw new IllegalArgumentException("FirebaseCallback must not be null");
        }

        this.firebaseMessaging.getToken()
                .addOnCompleteListener(task -> {
                    if (!task.isSuccessful()) {
                        Exception exception =
                                task.getException() != null
                                        ? task.getException()
                                        : new IllegalStateException("Unknown FCM error");

                        callback.onError(exception);
                        return;
                    }

                    String token = task.getResult();
                    Log.d(TAG, "FCM token: " + token);
                    if (token == null || token.isEmpty()) {
                        callback.onError(new IllegalStateException("FCM token is null or empty"));
                        return;
                    }

                    callback.onTokenReceived(token);
                });
    }
}