package com.oguerreiro.resilient.repository;

import java.util.List;
import java.util.Optional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.oguerreiro.resilient.domain.Period;
import com.oguerreiro.resilient.domain.enumeration.PeriodStatus;

/**
 * Spring Data JPA repository for the Period entity.
 */
@Repository
public interface PeriodRepository extends ResilientJpaRepository<Period, Long>, JpaRepository<Period, Long> {
  /* Interface ResilientJpaRepository eager fetching Override methods */
  /* **************************************************************** */
  @Override
  @Query(value = "select period from Period period left join fetch period.periodVersions", countQuery = "select count(period) from Period period")
  Page<Period> findAllWithEagerRelationships(Pageable pageable);

  @Override
  @Query("select period from Period period left join fetch period.periodVersions")
  List<Period> findAllWithEagerRelationships();

  @Override
  @Query("select period from Period period left join fetch period.periodVersions where period.id =:id")
  Optional<Period> findOneWithEagerRelationships(@Param("id") Long id);

  /**
   * Find a {@link Period} by its primary key with concurrency check ({@code version}).
   * 
   * @param  id
   * @param  version
   * @return
   */
  @Query("select period from Period period left join fetch period.periodVersions where period.id =:id and period.version=:version")
  Optional<Period> findByIdAndVersionWithRelationships(@Param("id") Long id, @Param("version") Integer version);

  List<Period> findAllByState(PeriodStatus state);
}
