package com.mosquito.project.permission;

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;
import java.util.Optional;

/**
 * 部门Repository
 */
@Repository
public interface DepartmentRepository extends JpaRepository<SysDepartment, Long> {

    /**
     * 根据父部门ID查询
     */
    List<SysDepartment> findByParentId(Long parentId);

    /**
     * 根据部门代码查询
     */
    Optional<SysDepartment> findByDeptCode(String deptCode);

    /**
     * 检查部门代码是否存在
     */
    boolean existsByDeptCode(String deptCode);

    /**
     * 递归查询指定部门及其所有下级部门ID
     * 使用WITH RECURSIVE实现（MySQL 8.0+支持）
     */
    @Query(value = "WITH RECURSIVE dept_tree AS (" +
            "  SELECT id FROM sys_departments WHERE id = :deptId " +
            "  UNION ALL " +
            "  SELECT d.id FROM sys_departments d " +
            "  INNER JOIN dept_tree dt ON d.parent_id = dt.id" +
            ") SELECT id FROM dept_tree", nativeQuery = true)
    List<Long> findAllDescendantDeptIds(@Param("deptId") Long deptId);
}
