package com.github.wxiaoqi.security.admin.feign.rest;

import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.admin.feign.dto.UserDTO;
import com.github.wxiaoqi.security.common.context.BaseContextHandler;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public interface UserRestInterface {
    public UserFeign getUserFeign();

    default HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    default AppUserDTO getAppUser(){
        return  getUserFeign().userDetailByToken(BaseContextHandler.getToken()).getData();
    }

    default void checkAppUser(){
        if(null == getAppUser()) {
            throw new BaseException(ResultCode.DB_OPERATION_FAIL_CODE);
        }
    }

    default UserDTO getAdminUserInfo() {
        if(getRequest().getHeader("Authorization") !=null) {
            return getUserFeign().userinfoByToken(getRequest().getHeader("Authorization")).getData();
        }else {
            return null;
        }
    }

    default void checkAdminUser(){
        if(null == getAdminUserInfo()) {
            throw new BaseException(ResultCode.DB_OPERATION_FAIL_CODE);
        }
    }
}
