package dev.zxq5.chatapp.android.data.repository

import dev.zxq5.chatapp.android.api.ChatClient
import dev.zxq5.chatapp.android.core.data.TokenStore
import dev.zxq5.chatapp.android.api.model.Message
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow

class ChatRepository(private val tokenStore: TokenStore) {
    
    private var _chatClient: ChatClient? = null
    private var _lastToken: String? = null

    private fun getChatClient(): ChatClient? {
        val token = tokenStore.get() ?: return null
        if (_chatClient == null || token != _lastToken) {
            _chatClient = ChatClient(token)
            _lastToken = token
        }
        return _chatClient
    }

    fun resetClient() {
        _chatClient = null
        _lastToken = null
    }

    fun getUserId() = tokenStore.getUserId()

    suspend fun sendMessage(channelId: Int, text: String) {
        val userId = tokenStore.getUserId() ?: return
        getChatClient()?.sendMessage(channelId, userId, text)
    }

    fun messageStream(channelId: Int): Flow<Message> {
        return getChatClient()?.messageStream(channelId) ?: emptyFlow()
    }
}
