package br.gov.sigefp.org.repository;

import br.gov.sigefp.org.domain.OrgUnit;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.EntityGraph;
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;
import java.util.UUID;

@Repository
public interface OrgUnitRepository extends JpaRepository<OrgUnit, UUID> {

    @EntityGraph(attributePaths = { "ministry", "parentUnit" })
    Page<OrgUnit> findAll(Pageable pageable);

    Optional<OrgUnit> findByCode(String code);

    boolean existsByCode(String code);

    @EntityGraph(attributePaths = { "ministry", "parentUnit" })
    List<OrgUnit> findByMinistryId(UUID ministryId);

    List<OrgUnit> findByParentUnitId(UUID parentUnitId);

    @Query("SELECT ou FROM OrgUnit ou WHERE ou.ministry.id = :ministryId AND ou.parentUnit IS NULL")
    List<OrgUnit> findRootUnitsByMinistryId(@Param("ministryId") UUID ministryId);

    @Query("SELECT ou FROM OrgUnit ou WHERE ou.ministry.id = :ministryId AND ou.parentUnit.id = :parentUnitId")
    List<OrgUnit> findByMinistryIdAndParentUnitId(@Param("ministryId") UUID ministryId,
            @Param("parentUnitId") UUID parentUnitId);
}
