package gaf3.core.services.token

import gaf3.core.data.ErrorResult
import gaf3.core.data.JsonResult
import gaf3.core.exception.BusinessError
import gaf3.core.services.token.service.TokenService
import org.springframework.util.Assert.hasText
import org.springframework.web.bind.annotation.*

@RestController
class ServiceTokenController(val service: TokenService) {

    @PostMapping(path = ["/gaf/token/{state}"])
    @ResponseBody
    fun create(@PathVariable("state") state: String, token: String?, userId: String?): ErrorResult {
        hasText(token, "token不能为空")
        service.putToken(state, token!!, userId)
        return ErrorResult(0)
    }

    @GetMapping(path = ["/gaf/token/{state}"])
    @ResponseBody
    fun fetch(@PathVariable("state") state: String): JsonResult<String> {
        return service.getToken(state)?.let {
            JsonResult(it)
        } ?: throw BusinessError(BusinessError.ERR_DATA_INVALID, "Token不存在或状态已失效")
    }

    @DeleteMapping(path = ["/gaf/token/{state}"])
    @ResponseBody
    fun remove(@PathVariable("state") state: String): ErrorResult {
        service.delToken(state)
        return ErrorResult()
    }
}