package com.example.elva.data.repository

import com.example.elva.data.api.UserApiService
import com.example.elva.data.models.user.UserProfile
import com.example.elva.util.AuthManager
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class UserRepository @Inject constructor(
    private val userApiService: UserApiService,
    private val authManager: AuthManager
) {

    suspend fun getCurrentUser(): Result<UserProfile> {
        return try {
            val token = authManager.getAccessToken()
            if (token.isNullOrEmpty()) {
                android.util.Log.w("UserRepository", "No auth token found")
                return Result.failure(Exception("No auth token found"))
            }

            android.util.Log.d("UserRepository", "Loading user profile with token: ${token.take(20)}...")
            val profile = userApiService.getCurrentUser("Bearer $token")
            android.util.Log.d("UserRepository", "Profile loaded: id=${profile.id}, username=${profile.username}")

            // Сохраняем полученные данные пользователя
            authManager.saveUserId(profile.id)
            profile.uuid?.let { authManager.saveUserUuid(it) }

            android.util.Log.d("UserRepository", "User data saved to AuthManager")

            Result.success(profile)
        } catch (e: Exception) {
            android.util.Log.e("UserRepository", "Error loading user profile", e)
            Result.failure(e)
        }
    }
}

