package de.votian.services.repository;

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

public interface ServiceHistoryRepository extends JpaRepository<ServiceHistory, Long> {

    @Query("SELECT sh FROM ServiceHistory sh WHERE sh.serviceId = :srvId AND sh.customerId = :csId " +
           "AND sh.headquartersId = :hqId AND sh.validFrom <= :date ORDER BY sh.validFrom DESC")
    Optional<ServiceHistory> findLatestPrice(@Param("srvId") Long srvId, @Param("csId") Long csId,
                                             @Param("hqId") Long hqId, @Param("date") LocalDateTime date);

    @Query("SELECT sh FROM ServiceHistory sh WHERE sh.serviceId = :srvId AND sh.serviceTypeId = :srvtId " +
           "AND sh.customerId = :csId AND sh.headquartersId = :hqId AND sh.validFrom <= :date " +
           "ORDER BY sh.validFrom DESC")
    List<ServiceHistory> findLatestPriceForType(@Param("srvId") Long srvId,
                                                @Param("srvtId") Long serviceTypeId,
                                                @Param("csId") Long customerId,
                                                @Param("hqId") Long headquartersId,
                                                @Param("date") LocalDateTime date);

    @Query("SELECT sh FROM ServiceHistory sh WHERE sh.headquartersId = :hqId AND sh.customerId = :csId " +
           "ORDER BY sh.serviceId, sh.serviceTypeId, sh.validFrom DESC")
    List<ServiceHistory> findForHqAndCustomer(@Param("hqId") Long hqId, @Param("csId") Long csId);
}
