package cn.reghao.bnt.web.admin.service;

import cn.reghao.bnt.web.admin.model.constant.RoleType;
import cn.reghao.bnt.web.admin.security.form.AccountAuthToken;
import cn.reghao.bnt.web.admin.model.po.User;
import cn.reghao.jutil.web.ServletUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author reghao
 * @date 2023-12-01 10:31:52
 */
public class UserContext {
    public static AccountAuthToken getAccountAuthToken() {
        Authentication authToken = SecurityContextHolder.getContext().getAuthentication();
        if (authToken instanceof AccountAuthToken) {
            return (AccountAuthToken) authToken;
        }

        return null;
    }

    public static User getUser() {
        Authentication authToken = SecurityContextHolder.getContext().getAuthentication();
        if (authToken instanceof AccountAuthToken) {
            return (User) authToken.getDetails();
        }

        return null;
    }

    public static int getUserId() {
        User user = getUser();
        return user != null ? user.getId() : -1;
    }

    public static String getUserRole() {
        User user = getUser();
        return user != null ? user.getRole().iterator().next() : RoleType.ROLE_ANONYMOUS.name();
    }

    /**
     * 设置通过 oss-sdk 登入的用户
     *
     * @param
     * @return
     * @date 2025-06-03 11:39:45
     */
    public static void setOssUser(User user) {
        String sessionId = ServletUtil.getSessionId();
        AccountAuthToken authToken = new AccountAuthToken(sessionId, false, user.getId(), "");
        authToken.setAuthenticated(true);
        Authentication auth = new AccountAuthToken(authToken, user);
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(auth);
    }
}
