package kr.co.accura.wbx.spring.rbac;

import kr.co.accura.wbx.spring.common.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

/**
 * WBX RBAC 권한 체크
 * Controller에서: @PreAuthorize("@wbx.check('TIMESHEET', 'VIEW')")
 */
@Component("wbx")
@RequiredArgsConstructor
public class PermissionEvaluator {

    private final RolePermissionRepository permRepo;

    /**
     * 모듈-액션 기반 권한 체크
     */
    @Cacheable(value = "permissions", key = "#module + ':' + #action + ':' + T(kr.co.accura.wbx.spring.common.SecurityUtils).getCurrentUserId()")
    public boolean check(String module, String action) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) return false;
        return permRepo.existsByUserIdAndModuleAndAction(userId, module, action);
    }

    /**
     * dept_scope 반환: 데이터 필터링 범위 결정
     */
    @Cacheable(value = "deptScopes", key = "#module + ':' + #action + ':' + T(kr.co.accura.wbx.spring.common.SecurityUtils).getCurrentUserId()")
    public DeptScope getScope(String module, String action) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) return DeptScope.OWN;
        return permRepo.findMaxDeptScope(userId, module, action)
                .orElse(DeptScope.OWN);
    }
}
