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

import android.util.Log
import com.zaojiao.app.core.auth.model.TokenModel
import com.zaojiao.app.core.auth.utils.AuthState
import com.zaojiao.app.core.auth.utils.AuthUtils
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach

class AuthRepository constructor(
    private val localAuthData: LocalAuthData,
    private val remoteTokenData: RemoteAuthData,
) {
    val token: Flow<TokenModel?> = localAuthData.token.onEach {
        AuthUtils._state = if (it == null) AuthState.OUT else AuthState.IN
    }

    val state: Flow<AuthState> = localAuthData.token.map {
        Log.e("AuthRepository", "state: ${if (it == null) "out" else "in"}")
        AuthUtils._state = if (it == null) AuthState.OUT else AuthState.IN
        if (it == null) AuthState.OUT else AuthState.IN
    }.distinctUntilChanged()

    suspend fun checkHasLogin(): Boolean {
        return token.first() != null
    }

    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()
    }
}