package com.aiwazian.messenger.services

import com.aiwazian.messenger.api.RetrofitInstance
import com.aiwazian.messenger.data.UserInfo
import com.aiwazian.messenger.data.UpdateProfileRequest
import com.aiwazian.messenger.data.UpdateUsernameRequest
import javax.inject.Inject

class UserService @Inject constructor() {
    
    suspend fun updateProfile(userInfo: UserInfo): Boolean {
        val response = RetrofitInstance.api.updateProfile(userInfo.toUpdateRequest())
        return response.isSuccessful
    }
    
    suspend fun getById(userId: Long): UserInfo? {
        val response = RetrofitInstance.api.getUserById(userId)
        return response.body()
    }
    
    suspend fun checkUsername(username: String): Boolean {
        val response = RetrofitInstance.api.checkUsername(username)
        return response.isSuccessful && response.body()?.available == true
    }
    
    suspend fun saveUsername(username: String): Boolean {
        val response = RetrofitInstance.api.saveUsername(
            UpdateUsernameRequest(username.ifBlank { null })
        )
        return response.isSuccessful
    }

    private fun UserInfo.toUpdateRequest() = UpdateProfileRequest(
        firstName = firstName,
        lastName = lastName.ifBlank { null },
        username = username,
        bio = bio.ifBlank { null },
        dateOfBirth = dateOfBirth
    )
}
