package com.mosquito.project.permission;

import com.mosquito.project.permission.entity.SysUserTokenEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

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

/**
 * 用户Token Repository
 */
@Repository
public interface UserTokenRepository extends JpaRepository<SysUserTokenEntity, Long> {

    Optional<SysUserTokenEntity> findByToken(String token);

    List<SysUserTokenEntity> findByUserId(Long userId);

    @Modifying
    @Query("DELETE FROM SysUserTokenEntity t WHERE t.expiresAt < ?1 OR t.userId = ?2")
    void deleteExpiredOrByUserId(LocalDateTime now, Long userId);

    @Modifying
    @Query("DELETE FROM SysUserTokenEntity t WHERE t.expiresAt < ?1")
    void deleteExpiredTokens(LocalDateTime now);
}
