package com.sonic.bear.lib.client;

import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.ImmutableMap;
import com.sonic.common.AppRuntime;
import com.sonic.common.auth.domains.Session;
import com.sonic.common.rpc.Result;
import com.sonic.common.rpc.RpcClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author code
 */
@Slf4j
@Service
public class UserSessionClient {

    private static final String URI_TOUCH_SESSION = "/api/auth/touch-session";

    private RpcClient rpcClient;
    private String host;

    public UserSessionClient(RpcClient rpcClient, AppRuntime appRuntime) {
        this.rpcClient = rpcClient;
        switch (appRuntime.getEnv()) {
            case dev:
                this.host = "http://dev-bear.svc.cloud";
                break;
            case local:
                this.host = "http://localhost:8080";
                break;
            case test:
                this.host = "http://test-bear-svc:8080";
                break;
            case product:
            default:
                this.host = "http://prod-bear-svc:8080";
        }
    }

    /**
     * 正常返回则表示该session处于活跃状态；抛出异常表示该会话已过期。
     * <p/>
     * LoadingCache.get，如果缓存中不存在，则调用load直接访问远程服务，并放入本地缓存。
     * 如果 load 抛出异常，get 会直接抛出 load 的异常
     * <p>
     *
     * @param token 用户会话TOKEN
     */
    public Session touchSession(final String token) {
        return rpcClient.post(host + URI_TOUCH_SESSION, ImmutableMap.of("token", token), new TypeReference<Result<Session>>(){});
    }

}
