package com.example.myapplication.database.entities.composeui

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication.database.entities.model.User
import com.example.myapplication.database.entities.repository.UserRepository
import kotlinx.coroutines.launch

class RegisterUserViewModel(private val userRepository: UserRepository) : ViewModel() {

    private val _users = MutableLiveData<List<User>>()
    val users: LiveData<List<User>> get() = _users

    fun setUserList() {
        viewModelScope.launch {
            _users.value = userRepository.getAllUsers()
        }
    }

    suspend fun insertUser(user: User) {
        userRepository.insertUser(user)
    }

    suspend fun registerUser(username: String, password: String): Boolean {
        if (password.isNotEmpty() && username.isNotEmpty()) {
            val existingUser = _users.value?.find { it.login == username }
            if (existingUser == null) {
                val newUser = User(null, username,"user" ,password)
                insertUser(newUser)
                setUserList()
                return true
            }
        }
        return false
    }
}