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.Unit;

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

  @Override
  @Query("select unit from Unit unit left join fetch unit.unitType")
  List<Unit> findAllWithEagerRelationships();

  @Override
  @Query("select unit from Unit unit left join fetch unit.unitType where unit.id =:id")
  Optional<Unit> findOneWithEagerRelationships(@Param("id") Long id);

  /* Custom UnitRepository methods */
  /* ***************************** */
  @Query("select unit from Unit unit left join fetch unit.unitType unitYpe where unitType.id=:unitTypeId")
  List<Unit> findAllByTypeWithToOneRelationships(@Param("unitTypeId") Long unitTypeId);

  Optional<Unit> findOneByCodeOrSymbol(String code, String symbol);

  @Query("""
        select unit from Unit unit, VariableUnits vu where vu.variable.id=:variableId AND vu.unit=unit
      """)
  List<Unit> findAllUnitsAllowedForVariable(@Param("variableId") Long variableId);

  @Query("""
        select unit from Unit unit, Variable v where v.id=:variableId AND v.baseUnit=unit
      """)
  List<Unit> findBaseUnitForVariable(@Param("variableId") Long variableId);
}
