package com.mosquito.project.persistence.repository;

import com.mosquito.project.persistence.entity.RiskAlertEntity;
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 RiskAlertRepository extends JpaRepository<RiskAlertEntity, Long> {

    Page<RiskAlertEntity> findByStatus(String status, Pageable pageable);

    Page<RiskAlertEntity> findByAlertType(String alertType, Pageable pageable);

    Page<RiskAlertEntity> findByRiskLevel(String riskLevel, Pageable pageable);

    @Query("SELECT a FROM RiskAlertEntity a WHERE " +
           "(:alertType IS NULL OR a.alertType = :alertType) AND " +
           "(:riskLevel IS NULL OR a.riskLevel = :riskLevel) AND " +
           "(:status IS NULL OR a.status = :status)")
    Page<RiskAlertEntity> findByFilters(
            @Param("alertType") String alertType,
            @Param("riskLevel") String riskLevel,
            @Param("status") String status,
            Pageable pageable);

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

    long countByStatus(String status);

    List<RiskAlertEntity> findByRelatedUserIdAndStatus(Long userId, String status);
}
