package auth.data.repository import auth.data.remote.api.AuthApi import auth.data.remote.dto.AuthRequest import auth.domain.model.AuthResult import auth.domain.repository.AuthRepository import core.network.ServerConfig import core.security.TokenManager import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import javax.inject.Inject class AuthRepositoryImpl @Inject constructor( private val api: AuthApi, private val tokenManager: TokenManager, private val serverConfig: ServerConfig ) : AuthRepository { private val _isAuthenticated = kotlinx.coroutines.flow.MutableStateFlow(tokenManager.getToken() != null) override suspend fun login(userName: String, password: String): Result { return try { val response = api.login(AuthRequest(userName, password)) val token = response.accessToken ?: return Result.failure(Exception("Token is null")) val userId = response.userId ?: "" tokenManager.saveToken(token, userId) _isAuthenticated.value = true fetchConfig() Result.success( AuthResult( token = token, userId = userId, userName = response.username ?: userName, displayName = response.displayName ?: response.username ?: userName, avatarUrl = null ) ) } catch (e: Exception) { Result.failure(e) } } override suspend fun register(userName: String, password: String): Result { return try { val response = api.register(AuthRequest(userName, password)) val token = response.accessToken ?: return Result.failure(Exception("Token is null")) val userId = response.userId ?: "" tokenManager.saveToken(token, userId) _isAuthenticated.value = true fetchConfig() Result.success( AuthResult( token = token, userId = userId, userName = response.username ?: userName, displayName = response.displayName ?: response.username ?: userName, avatarUrl = null ) ) } catch (e: Exception) { Result.failure(e) } } override suspend fun logout() { tokenManager.deleteToken() _isAuthenticated.value = false } override fun isAuthenticated(): Boolean { return _isAuthenticated.value } override fun isAuthenticatedFlow(): kotlinx.coroutines.flow.StateFlow { return _isAuthenticated.asStateFlow() } override suspend fun fetchConfig(): Result { return try { val config = api.getConfig() serverConfig.saveServerConfig(config) Result.success(Unit) } catch (e: Exception) { Result.failure(e) } } override suspend fun updatePushToken(token: String) { try { api.updatePushToken(token) } catch (e: Exception) { // Silent fail } } }