package com.mosquito.project.persistence.repository;

import com.mosquito.project.persistence.entity.RiskRuleEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface RiskRuleRepository extends JpaRepository<RiskRuleEntity, Long> {

    List<RiskRuleEntity> findByStatus(String status);

    List<RiskRuleEntity> findByRiskType(String riskType);

    @Query("SELECT r FROM RiskRuleEntity r WHERE " +
           "(:riskType IS NULL OR r.riskType = :riskType) AND " +
           "(:status IS NULL OR r.status = :status)")
    Page<RiskRuleEntity> findByFilters(
            @Param("riskType") String riskType,
            @Param("status") String status,
            Pageable pageable);

    /**
     * 带数据权限过滤的查询
     */
    @Query("SELECT r FROM RiskRuleEntity r WHERE " +
           "(:riskType IS NULL OR r.riskType = :riskType) AND " +
           "(:status IS NULL OR r.status = :status) AND " +
           "(:dataScope = 'ALL' OR " +
           "(:dataScope = 'DEPARTMENT' AND r.departmentId IN :deptIds) OR " +
           "(:dataScope = 'OWN' AND r.createdBy = :currentUserId))")
    Page<RiskRuleEntity> findByFiltersWithDataScope(
            @Param("riskType") String riskType,
            @Param("status") String status,
            @Param("dataScope") String dataScope,
            @Param("deptIds") List<Long> deptIds,
            @Param("currentUserId") Long currentUserId,
            Pageable pageable);

    @Query("SELECT r FROM RiskRuleEntity r WHERE r.status = 'ENABLED' ORDER BY r.priority DESC")
    List<RiskRuleEntity> findEnabledRulesOrderByPriority();

    /**
     * 带数据权限过滤的查询（无分页，用于导出）
     */
    @Query("SELECT r FROM RiskRuleEntity r WHERE " +
           "(:riskType IS NULL OR r.riskType = :riskType) AND " +
           "(:status IS NULL OR r.status = :status) AND " +
           "(:dataScope = 'ALL' OR " +
           "(:dataScope = 'DEPARTMENT' AND r.departmentId IN :deptIds) OR " +
           "(:dataScope = 'OWN' AND r.createdBy = :currentUserId))")
    List<RiskRuleEntity> findByFiltersWithDataScope(
            @Param("riskType") String riskType,
            @Param("status") String status,
            @Param("dataScope") String dataScope,
            @Param("deptIds") List<Long> deptIds,
            @Param("currentUserId") Long currentUserId);
}
