package kr.co.accura.wbx.spring.auth;

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 org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Optional;

@Repository
public interface RefreshTokenRepository extends JpaRepository<WbxRefreshToken, Long> {

    Optional<WbxRefreshToken> findByTokenHash(String tokenHash);

    @Modifying @Transactional
    @Query("UPDATE WbxRefreshToken t SET t.isRevoked = true WHERE t.userId = :userId")
    void revokeAllByUserId(@Param("userId") Long userId);

    @Modifying @Transactional
    @Query("DELETE FROM WbxRefreshToken t WHERE t.expiresAt < :now OR t.isRevoked = true")
    void deleteExpiredOrRevoked(@Param("now") LocalDateTime now);
}
