package com.lesingle.edu.common.security;

import com.lesingle.edu.common.enums.ErrorCode;
import com.lesingle.edu.common.enums.UserRole;
import com.lesingle.edu.common.exception.BusinessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Security Utilities
 */
public class SecurityUtils {

    private SecurityUtils() {
    }

    public static JwtPayload getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new BusinessException(ErrorCode.UNAUTHORIZED);
        }
        return (JwtPayload) authentication.getPrincipal();
    }

    public static Long getCurrentUserId() {
        return getCurrentUser().getUserId();
    }

    public static String getCurrentUsername() {
        return getCurrentUser().getUsername();
    }

    public static String getCurrentRole() {
        return getCurrentUser().getRole();
    }

    /**
     * 获取当前用户角色枚举
     */
    public static UserRole getCurrentRoleEnum() {
        return UserRole.fromCode(getCurrentRole());
    }

    public static Long getCurrentTenantId() {
        return getCurrentUser().getTenantId();
    }

    public static String getCurrentName() {
        return getCurrentUser().getName();
    }

    public static boolean isAdmin() {
        return UserRole.ADMIN == getCurrentRoleEnum();
    }

    public static boolean isSchool() {
        return UserRole.SCHOOL == getCurrentRoleEnum();
    }

    public static boolean isTeacher() {
        return UserRole.TEACHER == getCurrentRoleEnum();
    }

    public static boolean isParent() {
        return UserRole.PARENT == getCurrentRoleEnum();
    }

}
