package de.votian.services.repository;

import de.votian.services.entity.Courier;
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 CourierRepository extends JpaRepository<Courier, Long> {

    Optional<Courier> findByEid(String eid);

    List<Courier> findByHeadquartersId(Long hqId);

    Optional<Courier> findByUserId(Long userId);

    @Query("SELECT cr FROM Courier cr WHERE cr.sid = :sid AND cr.headquartersId = :hqId")
    Optional<Courier> findBySidAndHq(@Param("sid") String sid, @Param("hqId") Long hqId);

    @Query("SELECT cr FROM Courier cr WHERE cr.eid = :eid AND cr.headquartersId = :hqId")
    Optional<Courier> findByEidAndHq(@Param("eid") String eid, @Param("hqId") Long hqId);

    @Query("SELECT cr FROM Courier cr " +
           "JOIN Company cmp ON cr.companyId = cmp.id " +
           "JOIN User usr ON cr.userId = usr.id " +
           "WHERE cmp.archived = '0' AND cr.headquartersId = :hqId " +
           "AND (cr.eid LIKE %:search% OR cmp.comp LIKE %:search% OR cmp.match LIKE %:search% " +
           "OR usr.name LIKE %:search% OR usr.firstname LIKE %:search%) " +
           "ORDER BY usr.name, usr.firstname")
    List<Courier> searchCouriers(@Param("hqId") Long hqId, @Param("search") String search);
}
