package com.gnx.telemedicine.repository;

import com.gnx.telemedicine.model.PasswordHistory;
import com.gnx.telemedicine.model.UserModel;
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 java.time.Instant;
import java.util.List;
import java.util.UUID;

/**
 * Repository for password history operations.
 */
@Repository
public interface PasswordHistoryRepository extends JpaRepository<PasswordHistory, UUID> {
    
    /**
     * Find all password history entries for a user, ordered by creation date (newest first).
     */
    List<PasswordHistory> findByUserOrderByCreatedAtDesc(UserModel user);
    
    /**
     * Find recent password history entries for a user (last N passwords).
     */
    @Query("SELECT ph FROM PasswordHistory ph WHERE ph.user = :user ORDER BY ph.createdAt DESC")
    List<PasswordHistory> findRecentPasswordsByUser(@Param("user") UserModel user);
    
    /**
     * Check if a password hash exists in user's password history.
     */
    @Query("SELECT COUNT(ph) > 0 FROM PasswordHistory ph WHERE ph.user = :user AND ph.passwordHash = :passwordHash")
    boolean existsByUserAndPasswordHash(@Param("user") UserModel user, @Param("passwordHash") String passwordHash);
    
    /**
     * Delete old password history entries (older than specified days).
     */
    @Modifying
    @Query("DELETE FROM PasswordHistory ph WHERE ph.createdAt < :cutoffDate")
    void deleteOldPasswordHistory(@Param("cutoffDate") Instant cutoffDate);
    
    /**
     * Delete all password history for a user.
     */
    void deleteByUser(UserModel user);
    
    /**
     * Count password history entries for a user.
     */
    long countByUser(UserModel user);
}

