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.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.oguerreiro.resilient.domain.Period;
import com.oguerreiro.resilient.domain.PeriodVersion;

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

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

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

  /* Custom PeriodVersionRepository methods */
  /* ************************************** */
  @Query("select count(*) from PeriodVersion periodVersion where periodVersion.period =:period and periodVersion.state <> com.oguerreiro.resilient.domain.enumeration.PeriodVersionStatus.ENDED")
  long countNotEndedPeriodVersion(@Param("period") Period period);

  @Query("select max(periodVersion.periodVersion) from PeriodVersion periodVersion where periodVersion.period =:period")
  long maxPeriodVersion(@Param("period") Period period);

  @Query("select version from PeriodVersion version where version.period.id=:periodId order by version.periodVersion")
  List<PeriodVersion> findAllByPeriod(@Param("periodId") Long periodId);

  @Query("select version from PeriodVersion version where version.period.id=:periodId and version.state=com.oguerreiro.resilient.domain.enumeration.PeriodVersionStatus.ENDED ORDER BY version.periodVersion DESC")
  List<PeriodVersion> findEndedPeriodVersionsForPeriod(@Param("periodId") Long periodId);
}
