package cn.lihongjie.coal.deviceCategory.repository;

import cn.lihongjie.coal.base.dao.BaseRepository;
import cn.lihongjie.coal.deviceCategory.entity.DeviceCategoryEntity;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public interface DeviceCategoryRepository extends BaseRepository<DeviceCategoryEntity> {


    @Query(
            value = """


        
        select d.id as id,
         (select array_agg(e.id) from t_device e where e.category_id = any(self_and_children_ids('t_device_category', d.id, true))) as all_device_ids,
         (select array_agg(e.id) from t_device e where e.category_id = any(self_and_children_ids('t_device_category', d.id, false))) as children_device_ids,
            (select array_agg(e.id) from t_device e where e.category_id = d.id) as self_device_ids
         
         from t_device_category d where d.id in :ids

""", nativeQuery = true)
    List<Map> deviceIds(@Param("ids") List<String> ids);

    @Query("select exists(select 1 from DeviceEntity e where e.category.id in :ids)")
    boolean isLinked(@Param("ids") List<String> ids);
}
