package org.springblade.common.auth.permission;

import com.wn.common.datamodel.ResultDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class BackendInnerLoginUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(BackendInnerLoginUtil.class);
    
    private static final String PERMISSION_SERVICE = "http://permission-service";
    
    @Autowired
    private RestTemplate restTemplate;
    
    /******
     * 服务端内部登录功能， 用于支持当各个微服务之间存在权限依赖的场景， 如某个用户拥有服务A的权限，但没有服务B的权限，但是服务A内部会调用服务B的接口，
     * 则需要用内部全局账号来访问服务B，避免被服务B的权限拦截器拦截。
     * @return 返回值为内部账号的SessionId, 各业务可以自由决定传递原生的SessionId或者内部账号的SessionId来满足不同的场景
     * @see SessionIdContextUtil 
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public String innerLogin() {
        try {
            ResponseEntity<ResultDTO> resp = restTemplate.getForEntity(PERMISSION_SERVICE + "/sys/user/innerLogin",
                    ResultDTO.class, "any", "any");
            ResultDTO<String> resultDTO = resp.getBody();
            return resultDTO.getData();
        } catch (Exception e) {
            logger.error("BackendInnerLoginUtil.innerLogin error.", e);
            throw new RuntimeException(e);
        }
        
    }

}
