package com.magistr.app.repository;

import com.magistr.app.model.AuthLoginAttemptAudit;
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.transaction.annotation.Transactional;

import java.time.Instant;

public interface AuthLoginAttemptAuditRepository extends JpaRepository<AuthLoginAttemptAudit, Long> {

    @Modifying
    @Transactional
    @Query(value = """
            WITH cleanup_candidates AS (
                SELECT id
                FROM auth_login_attempt_audit
                WHERE occurred_at < :cutoff
                ORDER BY occurred_at, id
                FOR UPDATE SKIP LOCKED
                LIMIT :batchSize
            )
            DELETE FROM auth_login_attempt_audit audit
            USING cleanup_candidates candidate
            WHERE audit.id = candidate.id
            """, nativeQuery = true)
    int deleteCleanupBatch(@Param("cutoff") Instant cutoff,
                           @Param("batchSize") int batchSize);
}
