package cn.novalon.gym.manage.db.dao;

import cn.novalon.gym.manage.db.entity.SysPermissionEntity;
import org.springframework.data.domain.Sort;
import org.springframework.data.r2dbc.repository.R2dbcRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Repository
public interface SysPermissionDao extends R2dbcRepository<SysPermissionEntity, Long> {

    Mono<SysPermissionEntity> findByIdAndDeletedAtIsNull(Long id);

    Mono<SysPermissionEntity> findByPermissionCodeAndDeletedAtIsNull(String permissionCode);

    Flux<SysPermissionEntity> findByDeletedAtIsNull();

    Flux<SysPermissionEntity> findByDeletedAtIsNull(Sort sort);

    Mono<Long> countByDeletedAtIsNull();

    Mono<Boolean> existsByPermissionCodeAndDeletedAtIsNull(String permissionCode);

    @org.springframework.data.r2dbc.repository.Query("""
        SELECT p.* FROM sys_permission p
        INNER JOIN sys_role_permission rp ON p.id = rp.permission_id
        WHERE rp.role_id = :roleId AND p.deleted_at IS NULL
        """)
    Flux<SysPermissionEntity> findByRoleId(Long roleId);

    @org.springframework.data.r2dbc.repository.Query("""
        SELECT DISTINCT p.* FROM sys_permission p
        INNER JOIN sys_role_permission rp ON p.id = rp.permission_id
        WHERE rp.role_id IN (:roleIds) AND p.deleted_at IS NULL
        """)
    Flux<SysPermissionEntity> findByRoleIds(java.util.List<Long> roleIds);
}