package com.imprimelibros.erp.auth;

import java.time.LocalDateTime;
import java.util.Optional;
import org.springframework.data.jpa.repository.*;
import java.util.List;

public interface PasswordResetTokenRepository extends JpaRepository<PasswordResetToken, Long> {

    // Para validar un token en el reset
    @Query("""
        SELECT t FROM PasswordResetToken t
        WHERE t.userId = :userId
          AND t.tokenHash = :tokenHash
          AND t.usedAt IS NULL
          AND t.expiresAt > :now
    """)
    Optional<PasswordResetToken> findValidByUserAndHash(Long userId, String tokenHash, LocalDateTime now);

    // Invalida cualquier token activo del usuario
    @Modifying
    @Query("""
        UPDATE PasswordResetToken t
           SET t.usedAt = :now
         WHERE t.userId = :userId
           AND t.usedAt IS NULL
           AND t.expiresAt > :now
    """)
    int invalidateActiveTokens(Long userId, LocalDateTime now);

    // (Opcional) lista de activos, por si quieres inspeccionarlos
    @Query("""
        SELECT t FROM PasswordResetToken t
        WHERE t.userId = :userId
          AND t.usedAt IS NULL
          AND t.expiresAt > :now
        ORDER BY t.createdAt DESC
    """)
    List<PasswordResetToken> findAllActiveForUser(Long userId, LocalDateTime now);
}
