package com.zaojiao.app.core.auth.data

import com.zaojiao.app.core.auth.model.TokenModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first

class AuthRepository constructor(
    private val localAuthData: LocalAuthData,
    private val remoteTokenData: RemoteAuthData,
) {
    val token: Flow<TokenModel?> = localAuthData.token

    suspend fun updateToken(token: TokenModel) {
        localAuthData.updateToken(token)
    }

    suspend fun refreshToken(): TokenModel? {
        val current = token.first()
        return if (current == null) {
            null
        } else {
            val token = remoteTokenData.refreshToken(current.refreshToken)
            if (token == null) {
                localAuthData.clearToken()
            } else {
                localAuthData.updateToken(token)
            }
            return token
        }
    }

    suspend fun clearToken() {
        localAuthData.clearToken()
    }
}