package dev.ulfrx.recipe.auth

import androidx.compose.runtime.snapshotFlow
import dev.lokksmith.client.request.flow.AuthFlow
import dev.lokksmith.client.request.flow.AuthFlowResultProvider
import dev.lokksmith.compose.AuthFlowLauncher
import kotlinx.coroutines.flow.first

/**
 * Adapter that converts Lokksmith's Compose-native [AuthFlowLauncher] (state-based)
 * into a suspending [AuthBrowser] (one-shot await). The screen creates this once via
 * `remember(launcher)` and passes it to the ViewModel, so call sites stay plain
 * `suspend`-friendly.
 */
class ComposeAuthBrowser(
    private val launcher: AuthFlowLauncher,
) : AuthBrowser {
    override suspend fun launchAndAwait(initiation: AuthFlow.Initiation): AuthFlowResultProvider.Result {
        launcher.launch(initiation)
        return snapshotFlow { launcher.result }
            .first { result ->
                result is AuthFlowResultProvider.Result.Success ||
                    result is AuthFlowResultProvider.Result.Cancelled ||
                    result is AuthFlowResultProvider.Result.Error
            }
    }
}
