package gaf3.core.services.token.service

import gaf3.core.cache.CacheService
import gaf3.core.exception.BusinessError
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Service


@Service
class TokenService (@Qualifier("gafTokenCacheService") val cacheService : CacheService) {

    /**
     * 保存Token状态
     */
    fun putToken(state: String, token: String, userId: String? = null) {
        if (userId != null) {
            // 更新用户绑定记录
            getToken(userId)?.let { putToken(it, "obsolete") }
            cacheService.setCache(userId, state)
        }
        cacheService.setCache(state, token)
    }

    /**
     * 通过state换取Token
     */
    fun getToken(state: String): String? {
        return cacheService.getCache(state)?.let {
            if(it == "obsolete") throw BusinessError(BusinessError.ERR_TOKEN_OBSOLETE, "Token已被替代")
            it
        }
    }

    /**
     * 通过state换取Token
     */
    fun delToken(state: String) {
        return cacheService.delCache(state)
    }
}