package dev.inmo.postssystem.features.auth.client.ui

import dev.inmo.postssystem.features.auth.common.AuthCreds
import dev.inmo.postssystem.features.common.common.UIViewModel
import dev.inmo.postssystem.features.users.common.Username
import kotlinx.coroutines.flow.StateFlow

class AuthUIViewModel(
    private val model: AuthUIModel
) : UIViewModel<AuthUIState> {
    override val currentState: StateFlow<AuthUIState>
        get() = model.currentState

    private fun checkIncomingData(
        serverUrl: String,
        username: String,
        password: String
    ): Boolean {
        return serverUrl.isNotBlank() && username.isNotBlank() && password.isNotBlank()
    }

    suspend fun initAuth(
        serverUrl: String,
        username: String,
        password: String
    ) {
        if (checkIncomingData(serverUrl, username, password)) {
            model.initAuth(
                serverUrl.takeIf { it.startsWith("http") } ?: "http://$serverUrl",
                AuthCreds(Username(username), password)
            )
        }
    }
}
