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

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Repository
public interface RolePermissionRepository extends JpaRepository<RolePermission, Long> {

    @Query("""
        SELECT CASE WHEN COUNT(rp) > 0 THEN true ELSE false END
        FROM RolePermission rp
        JOIN kr.co.accura.wbx.spring.rbac.WbxUserRole ur ON rp.roleId = ur.roleId
        WHERE ur.userId = :userId AND rp.module = :module AND rp.action = :action
    """)
    boolean existsByUserIdAndModuleAndAction(@Param("userId") Long userId,
                                             @Param("module") String module,
                                             @Param("action") String action);

    @Query("""
        SELECT rp.deptScope FROM RolePermission rp
        JOIN kr.co.accura.wbx.spring.rbac.WbxUserRole ur ON rp.roleId = ur.roleId
        WHERE ur.userId = :userId AND rp.module = :module AND rp.action = :action
        ORDER BY CASE rp.deptScope WHEN 'COMPANY' THEN 3 WHEN 'DEPT' THEN 2 ELSE 1 END DESC
    """)
    Optional<DeptScope> findMaxDeptScope(@Param("userId") Long userId,
                                         @Param("module") String module,
                                         @Param("action") String action);

    List<RolePermission> findByRoleId(Long roleId);

    @Modifying
    @Transactional
    void deleteByRoleId(Long roleId);
}
