package cz.muni.fi.pa165.core.user;

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 java.time.Instant;
import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, String> {
	// @Modifying
	// @Query("UPDATE User u set u.username= :#{#user.username}, u.password= :#{#user.password}, u.lastName= :#{#user.lastName}, u.firstName= :#{#user.firstName}, u.email= :#{#user.email} where u.id = :#{#id}")
	// int update(@Param("user") User user, @Param("id") String id);


	@Query("Select SUM(m.consumptionKWH) " +
			"From User u " +
			"INNER JOIN Role r " +
			"INNER JOIN HouseRole hr " +
			"INNER JOIN House h " +
			"INNER JOIN SmartMeter s " +
			"INNER JOIN Metrics m " +
			"where u.id = :#{#userId} and h.id = :#{#houseId} and m.createdAt >= :#{#startTime} and m.createdAt <= :#{#endTime}")
	Double getStatisticsData(@Param("userId") String userId,
							 @Param("houseId") String houseId,
							 @Param("startTime") Instant startTime,
							 @Param("endTime") Instant endTime);

	Optional<User> findByUsername(String username);

	Optional<User> findByIdAndPassword(String id, String password);

    Optional<Object> findByEmail(String username);

	@Query("Select u " +
			"From User u " +
			"JOIN FETCH u.rolesList " +
			"where u.email = :#{#email}")
	Optional<User> findUserWithRoles(String email);
}
