package com.ga.common.aop;

import com.ga.common.annotation.RequirePermission;
import com.ga.common.exception.BizException;
import com.ga.common.exception.ErrorCode;
import com.ga.common.menu.PermissionChecker;
import com.ga.common.util.SecurityUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * @RequirePermission 처리. 현재 사용자의 (menu, perm) 권한을 검증한다.
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class PermissionAspect {

    private final PermissionChecker permissionChecker;

    @Before("@annotation(com.ga.common.annotation.RequirePermission)")
    public void check(org.aspectj.lang.JoinPoint jp) {
        Long userId = SecurityUtil.getCurrentUserId();
        if (userId == null) throw new BizException(ErrorCode.UNAUTHORIZED);

        MethodSignature sig = (MethodSignature) jp.getSignature();
        RequirePermission ann = sig.getMethod().getAnnotation(RequirePermission.class);
        if (ann == null) return;

        if (!permissionChecker.hasPermission(userId, ann.menu(), ann.perm())) {
            log.warn("Permission denied: userId={}, menu={}, perm={}", userId, ann.menu(), ann.perm());
            throw new BizException(ErrorCode.FORBIDDEN);
        }
    }
}
