package uz.ssd.mobiuz.network.repository

import android.content.Context
import dagger.hilt.android.qualifiers.ApplicationContext
import uz.ssd.mobiuz.model.SharedPref
import uz.ssd.mobiuz.model.UserAuth
import uz.ssd.mobiuz.network.api.ApiService
import uz.ssd.mobiuz.network.model.Action
import uz.ssd.mobiuz.network.model.UiStateObject
import uz.ssd.mobiuz.utils.extensions.userMessage
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class AuthRepository @Inject constructor(
    private val apiService: ApiService,
    private val pref: SharedPref,
    @ApplicationContext val context: Context
) {

    suspend fun loginUser(data: UserAuth): UiStateObject<Action> {
        return try {
            val res = apiService.checkPhone(data)
            if (res.status)
                UiStateObject.SUCCESS(res.data ?: Action())
            else{
                var error = ""
                res.errors.forEach {
                    error += it.message
                }
                UiStateObject.ERROR(error)
            }

        } catch (e: Exception) {
            UiStateObject.ERROR(e.userMessage(context))
        }
    }

    suspend fun registerUser(data: UserAuth): UiStateObject<String> {
        return try {
            val res = apiService.register(data)
            if (res.status)
                UiStateObject.SUCCESS(res.message)
            else UiStateObject.ERROR(res.message)

        } catch (e: Exception) {
            UiStateObject.ERROR(e.userMessage(context))
        }
    }

    suspend fun checkSMSCode(data: UserAuth): UiStateObject<String> {
        return try {
            val res = apiService.checkSMSCode(data)
            if (res.status){
                pref.setUserToken(res.data?.token)
                UiStateObject.SUCCESS(res.message)
            }
            else UiStateObject.ERROR(res.message)

        } catch (e: Exception) {
            UiStateObject.ERROR(e.userMessage(context))
        }
    }

}