package com.lesingle.creation.util;

import com.lesingle.creation.common.exception.BusinessException;
import com.lesingle.creation.common.security.UserPrincipal;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * 用户上下文工具类
 *
 * @author lesingle
 * @since 1.0.0
 */
@Component
public class SecurityUtils {

    /**
     * 获取当前登录用户 ID
     *
     * @return 用户 ID
     */
    public Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new BusinessException("用户未登录");
        }

        Object principal = authentication.getPrincipal();
        if (principal instanceof UserPrincipal) {
            return ((UserPrincipal) principal).getUserId();
        }
        throw new BusinessException("获取用户 ID 失败");
    }

    /**
     * 获取当前登录用户 ID（字符串格式）
     * <p>
     * 用于 MyBatis-Plus 自动填充场景，非登录场景返回 "0"
     *
     * @return 用户 ID（字符串格式）
     */
    public String getCurrentUserIdStr() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                return "0";
            }

            Object principal = authentication.getPrincipal();
            if (principal instanceof UserPrincipal) {
                return String.valueOf(((UserPrincipal) principal).getUserId());
            }
            return "0";
        } catch (Exception e) {
            return "0";
        }
    }

    /**
     * 获取当前登录用户名
     * <p>
     * 用于 MyBatis-Plus 自动填充审计字段，非登录场景返回 "system"
     *
     * @return 用户名
     */
    public String getCurrentUsernameStr() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                return "system";
            }

            Object principal = authentication.getPrincipal();
            if (principal instanceof UserPrincipal) {
                return ((UserPrincipal) principal).getUsername();
            }
            return "system";
        } catch (Exception e) {
            return "system";
        }
    }

    /**
     * 获取当前租户 ID
     *
     * @return 租户 ID
     */
    public Long getCurrentTenantId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new BusinessException("用户未登录");
        }

        Object principal = authentication.getPrincipal();
        if (principal instanceof UserPrincipal) {
            return ((UserPrincipal) principal).getTenantId();
        }
        throw new BusinessException("获取租户 ID 失败");
    }

    /**
     * 获取当前登录用户名
     *
     * @return 用户名
     */
    public String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new BusinessException("用户未登录");
        }

        Object principal = authentication.getPrincipal();
        if (principal instanceof UserPrincipal) {
            return ((UserPrincipal) principal).getDisplayName();
        }
        throw new BusinessException("获取用户名失败");
    }

    /**
     * 判断当前用户是否为超级管理员
     *
     * @return 是否为超级管理员
     */
    public boolean isSuperAdmin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }

        // 检查是否有 super_admin 角色
        return authentication.getAuthorities().stream()
            .anyMatch(grantedAuthority -> "ROLE_super_admin".equals(grantedAuthority.getAuthority()));
    }

    /**
     * 判断当前用户是否为超级租户
     *
     * @return 是否为超级租户
     */
    public boolean isSuperTenant() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }

        Object principal = authentication.getPrincipal();
        if (principal instanceof UserPrincipal) {
            return ((UserPrincipal) principal).isSuperTenant();
        }
        return false;
    }

    /**
     * 获取当前租户编码
     *
     * @return 租户编码
     */
    public String getCurrentTenantCode() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new BusinessException("用户未登录");
        }

        Object principal = authentication.getPrincipal();
        if (principal instanceof UserPrincipal) {
            return ((UserPrincipal) principal).getTenantCode();
        }
        throw new BusinessException("获取租户编码失败");
    }

}
