package com.aiosman.riderpro.utils

import android.content.Context
import androidx.credentials.Credential
import androidx.credentials.CredentialManager
import androidx.credentials.CustomCredential
import androidx.credentials.GetCredentialRequest
import androidx.credentials.GetCredentialResponse
import com.google.android.libraries.identity.googleid.GetGoogleIdOption
import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential


fun handleGoogleSignIn(result: GetCredentialResponse, onLoginWithGoogle: (String) -> Unit) {
    val credential: Credential = result.credential

    if (credential is CustomCredential) {
        if (GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL.equals(credential.type)) {
            val googleIdTokenCredential: GoogleIdTokenCredential =
                GoogleIdTokenCredential.createFrom(credential.data)
            onLoginWithGoogle(googleIdTokenCredential.idToken)
        }
    }
}

suspend fun GoogleLogin(context: Context, onLoginWithGoogle: (String) -> Unit) {
    val credentialManager = CredentialManager.create(context)
    val googleIdOption: GetGoogleIdOption = GetGoogleIdOption.Builder()
        .setServerClientId("987156664714-3bpf58ldhhr0m474ep48l668ngdn7860.apps.googleusercontent.com")
        .setFilterByAuthorizedAccounts(false)
        .build()
    val request = GetCredentialRequest.Builder().addCredentialOption(googleIdOption)
        .build()

    credentialManager.getCredential(context, request).let {
        handleGoogleSignIn(it, onLoginWithGoogle)
    }
}