package com.greenorange.promotion.aop;


import com.greenorange.promotion.annotation.AuthCheck;
import com.greenorange.promotion.common.ErrorCode;
import com.greenorange.promotion.constant.UserConstant;
import com.greenorange.promotion.exception.BusinessException;
import com.greenorange.promotion.model.entity.User;
import com.greenorange.promotion.model.enums.UserRoleEnum;
import com.greenorange.promotion.service.user.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 权限校验AOP
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 执行拦截
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 接口的权限
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //当前登录用户
        User loginUser = userService.getLoginUser(request);
        //必须有该权限才通过
        if (StringUtils.isNotBlank(mustRole)) {
            //mustUserRoleEnum是接口权限
            UserRoleEnum mustUserRoleEnum = UserRoleEnum.getEnumByValues(mustRole);
            if(mustUserRoleEnum == null) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            //用户权限
            String userRole = loginUser.getUserRole();
            //根据用户角色获取封装后的枚举类对象
            UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValues(userRole);

            //如果被封号，直接拒绝
            if (UserRoleEnum.BAN.equals(userRoleEnum)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }

            //如果接口需要Boss权限，则需要判断用户是否是boss管理员
            if (UserRoleEnum.BOSS.equals(mustUserRoleEnum)) {
                if (!mustRole.equals(userRole)) {
                    throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
                }
            }
            //如果接口需要管理员权限，则需要判断用户是否是boss或者admin管理员
            if (UserRoleEnum.ADMIN.equals(mustUserRoleEnum)) {
                if (!mustRole.equals(userRole) && !userRole.equals(UserConstant.BOSS_ROLE)) {
                    throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
                }
            }
        }
        //通过权限校验，放行
        return joinPoint.proceed();
    }

}
