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 javax.inject.Inject class AuthRepositoryImpl @Inject constructor( private val api: AuthApi, private val tokenManager: TokenManager, private val serverConfig: ServerConfig ) : AuthRepository { 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")) tokenManager.saveToken(token) fetchConfig() Result.success( AuthResult( token = token, userId = response.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")) tokenManager.saveToken(token) fetchConfig() Result.success( AuthResult( token = token, userId = response.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() } override suspend fun fetchConfig(): Result { return try { val config = api.getConfig() serverConfig.saveServerConfig(config) Result.success(Unit) } catch (e: Exception) { Result.failure(e) } } }