package com.lesingle.security.aspect;

import com.lesingle.common.exception.BusinessException;
import com.lesingle.common.enums.ErrorCode;
import com.lesingle.common.util.SecurityUtil;
import com.lesingle.security.annotation.RequirePermission;
import com.lesingle.security.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Set;

/**
 * 权限校验切面
 * 超管（super_admin 角色）绕过所有权限检查
 * 多个权限之间为 OR 关系
 */
@Slf4j
@Aspect
@Component
public class PermissionAspect {

    @Before("@annotation(requirePermission)")
    public void checkPermission(JoinPoint joinPoint, RequirePermission requirePermission) {
        LoginUser currentUser = SecurityUtil.getCurrentUser();
        if (currentUser == null) {
            throw BusinessException.of(ErrorCode.UNAUTHORIZED);
        }

        // 超管绕过权限检查
        if (currentUser.isSuperAdmin()) {
            return;
        }

        String[] requiredPermissions = requirePermission.value();
        Set<String> userPermissions = currentUser.getPermissions();

        if (userPermissions == null || userPermissions.isEmpty()) {
            log.warn("权限校验失败，用户：{}，所需权限：{}", currentUser.getUsername(), Arrays.toString(requiredPermissions));
            throw BusinessException.of(ErrorCode.FORBIDDEN);
        }

        // OR 逻辑：拥有任一权限即可
        boolean hasPermission = Arrays.stream(requiredPermissions)
                .anyMatch(userPermissions::contains);

        if (!hasPermission) {
            log.warn("权限校验失败，用户：{}，所需权限：{}，用户权限：{}",
                    currentUser.getUsername(), Arrays.toString(requiredPermissions), userPermissions);
            throw BusinessException.of(ErrorCode.FORBIDDEN);
        }
    }
}
