package de.votian.services.repository;

import de.votian.services.entity.CostCenter;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.Optional;

public interface CostCenterRepository extends JpaRepository<CostCenter, Long> {

    List<CostCenter> findByCustomerId(Long customerId);

    Optional<CostCenter> findByCustomerIdAndName(Long customerId, String name);

    Optional<CostCenter> findFirstByCustomerIdAndParentIdIsNull(Long customerId);

    @Query("SELECT csc FROM CostCenter csc WHERE csc.customerId = :csId AND csc.visible = '1'")
    List<CostCenter> findVisibleByCustomerId(@Param("csId") Long csId);

    @Query(value = "SELECT c.* " +
            "FROM costcenter c " +
            "JOIN customer cs ON cs.cs_id = c.cs_id " +
            "WHERE cs.hq_id = :hqId " +
            "  AND c.csc_visible = 1 " +
            "  AND COALESCE(c.csc_is_extern, 0) <> 1",
            nativeQuery = true)
    List<CostCenter> findVisibleNonExternByHeadquartersId(@Param("hqId") Long hqId);

    @Query("SELECT csc FROM CostCenter csc WHERE csc.path LIKE %:pathFragment% AND csc.customerId = :csId")
    List<CostCenter> findByPathContainingAndCustomerId(@Param("pathFragment") String pathFragment, @Param("csId") Long csId);
}
