package org.codiki.core.repositories;

import java.util.Optional;

import javax.transaction.Transactional;

import org.codiki.core.entities.persistence.User;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends CrudRepository<User, Long> {
	
	Optional<User> findByEmail(@Param("email") final String pEmail);
	
	/**
	 * Checks if the password in parameters is the passwords of the user in
	 * database.
	 * 
	 * @param pId
	 *            The user id.
	 * @param pPassword
	 *            The password to check.
	 * @return {@code true} if the password is the user password in database,
	 *         {@code false} otherwise.
	 */
	@Query(value = "SELECT CASE WHEN EXISTS(" + 
			"	SELECT id FROM \"user\" WHERE id = :id AND password = :password" + 
			") THEN TRUE ELSE FALSE END", nativeQuery = true)
	boolean checkPassword(@Param("id") final Long pId, @Param("password") final String pPassword);
	
	@Query(value = "UPDATE \"user\" SET password = :password WHERE id = :id", nativeQuery = true)
	@Transactional
	@Modifying
	void updatePassword(@Param("id") final Long pId, @Param("password") final String pPassword);
}
