package de.votian.services.repository;

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

    Optional<Customer> findByEid(String eid);

    List<Customer> findByHeadquartersId(Long hqId);

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

    @Query("SELECT MAX(CAST(SUBSTRING(c.eid, :prefixLen + 1, 5) AS int)) FROM Customer c WHERE SUBSTRING(c.eid, 1, :prefixLen) = :prefix")
    Integer findMaxEidNumber(@Param("prefix") String prefix, @Param("prefixLen") int prefixLen);

    @Query("SELECT cs FROM Customer cs " +
           "JOIN Company cmp ON cs.companyId = cmp.id " +
           "JOIN Employee emp ON cs.adminEmployeeId = emp.id " +
           "JOIN User usr ON emp.userId = usr.id " +
           "WHERE cmp.archived = '0' AND cs.headquartersId = :hqId " +
           "AND (cs.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 cmp.comp")
    List<Customer> searchCustomers(@Param("hqId") Long hqId, @Param("search") String search);
}
