package de.votian.services.repository;

import de.votian.services.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {

    Optional<User> findByAccount(String account);

    @Query(value = "SELECT * FROM user WHERE usr_account = :account AND usr_password = PASSWORD(:password) LIMIT 1",
            nativeQuery = true)
    Optional<User> authenticate(@Param("account") String account, @Param("password") String password);

    @Query(value = "SELECT * FROM user WHERE usr_id = :userId AND usr_password = PASSWORD(:password) LIMIT 1",
            nativeQuery = true)
    Optional<User> authenticateById(@Param("userId") Long userId, @Param("password") String password);

    Optional<User> findByEmail(String email);

    List<User> findByEmail(String email, org.springframework.data.domain.Sort sort);

    @Query("SELECT u FROM User u WHERE u.account = :account AND u.id <> :excludeId")
    Optional<User> findByAccountExcludingId(@Param("account") String account, @Param("excludeId") Long excludeId);

    @Query("SELECT u FROM User u JOIN Headquarters hq ON u.headquartersId = hq.id " +
           "WHERE u.email = :email")
    List<User> findByEmailWithHq(@Param("email") String email);

    @Query("SELECT u FROM User u WHERE u.type = :type AND u.headquartersId = :hqId " +
           "ORDER BY LOWER(u.name), LOWER(u.firstname), u.id")
    List<User> findByTypeAndHeadquartersIdOrderByNameAscFirstnameAsc(@Param("type") Integer type,
                                                                     @Param("hqId") Long headquartersId);

    @Query("SELECT DISTINCT hq.mnemonic, u.name, u.firstname, u.type " +
           "FROM User u JOIN Headquarters hq ON u.headquartersId = hq.id " +
           "WHERE FUNCTION('RIGHT', u.birthdate, 5) = FUNCTION('RIGHT', CURRENT_DATE, 5) " +
           "ORDER BY u.type, u.name")
    List<Object[]> findBirthdaysToday();

    @Modifying
    @Query(value = "UPDATE user SET usr_password = PASSWORD(:password), usr_password_modify = CURRENT_TIMESTAMP " +
            "WHERE usr_id = :userId", nativeQuery = true)
    int updatePasswordWithMysqlFunction(@Param("userId") Long userId, @Param("password") String password);
}
