package com.example.exvesta.Screans

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.exvesta.domain.utils.Constants
import io.github.jan.supabase.gotrue.auth
import io.github.jan.supabase.gotrue.providers.builtin.Email
import io.github.jan.supabase.gotrue.providers.builtin.OTP

import kotlinx.coroutines.launch

class MainViewModel(): ViewModel() {
    private val _loginResult = MutableLiveData<Boolean>()
    val loginResult: LiveData<Boolean> = _loginResult

    fun onSignInEmailCode(emailUser: String) {
        viewModelScope.launch {
            try {
                Constants.supabase.auth.signInWith(OTP) {
                    email = emailUser
                    createUser = false
                }

            } catch (e: Exception) {
                println(e.message.toString())

            }

        }
    }

    fun onSignInEmailPassword(emailUser: String, passwordUser: String): Boolean {
        viewModelScope.launch {
            try {
                val user = Constants.supabase.auth.signInWith(Email) {
                    email = emailUser
                    password = passwordUser
                }
                println(user.toString())
                println(Constants.supabase.auth.currentUserOrNull()!!.id)
                println("Success")
                _loginResult.postValue(true)
            } catch (e: Exception) {
                println("Error")
                println(e.message.toString())
                _loginResult.postValue(false)
            }
        }
        return _loginResult.value ?: false
    }
    fun onSignUpEmail(emailUser: String, passwordUser: String): Boolean {
        viewModelScope.launch {
            try{
                var  user =  Constants.supabase.auth.signUpWith(Email) {
                    email = emailUser
                    password = passwordUser
                }
                println(user.toString())
                println(Constants.supabase.auth.currentUserOrNull()!!.id)
                println("Success")
                _loginResult.postValue(true)
            }
            catch (e: Exception) {
                println("Error")
                println(e.message.toString())
                _loginResult.postValue(false)
            }

        }
        return _loginResult.value ?: false
    }
}