package com.bytesw.bytebot.repository;


import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import com.bytesw.bytebot.model.BusinessParameterConfiguration;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

import java.math.BigInteger;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;


public interface BusinessParameterConfigurationRepository extends CrudRepository<BusinessParameterConfiguration, BigInteger>, JpaSpecificationExecutor<BusinessParameterConfiguration> {
    @Query("select b from BusinessParameterConfiguration b where b.businessParameter.key = :key and ((b.from < :fromDate and b.to >= :fromDate) OR (b.to is null))")
    List<BusinessParameterConfiguration> findValidByKey(@Param("key") String key, @Param("fromDate") OffsetDateTime fromDate);

    @Query("select b from BusinessParameterConfiguration b where b.businessParameter.key = :key and ((b.from < :currentDate and b.to >= :currentDate) OR (b.from < :currentDate and b.to is null))")
    Optional<BusinessParameterConfiguration> findCurrentValueByKey(@Param("key") String key, @Param("currentDate") OffsetDateTime currentDate);

    @Query("select b from BusinessParameterConfiguration b where b.businessParameter.id = :id")
    List<BusinessParameterConfiguration> findBusinessParameterConfigurationListByBusinessParameter(@Param("id") BigInteger id);

    @Query("select b from BusinessParameterConfiguration b where b.businessParameter.id = :id and (b.to > :toDate or b.to is null) order by b.from desc")
    List<BusinessParameterConfiguration> findBusinessParameterConfigurationListByBusinessParameterWithLowestDateFrom(@Param("id") BigInteger id, @Param("toDate") OffsetDateTime toDate);
}
