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

import dev.zxq5.chatapp.android.api.ChatClient
import dev.zxq5.chatapp.android.api.model.ChatEvent
import dev.zxq5.chatapp.android.core.data.TokenStore
import dev.zxq5.chatapp.android.api.model.Message
import dev.zxq5.chatapp.android.api.model.SpaceDto
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 var _lastActiveChannel: Long? = 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 getLastActiveChannel(): Long? {
        return _lastActiveChannel
    }

    fun getUserId() = tokenStore.getUserId()

    suspend fun getAccessibleChannels(): List<SpaceDto> {
        return getChatClient()?.getAccessibleChannels() ?: emptyList()
    }

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

    fun eventStream(channelId: Long): Flow<ChatEvent> {
        _lastActiveChannel = channelId
        return getChatClient()?.eventStream(channelId) ?: emptyFlow()
    }
}
