package ru.soune.nocopy.service.auth;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import ru.soune.nocopy.entity.user.AuthToken;
import ru.soune.nocopy.repository.AuthTokenRepository;

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

@Slf4j
@Component
@RequiredArgsConstructor
public class CleanupTokenSessionsService {
    @Autowired
    private AuthTokenRepository authTokenRepository;

    @Value("${file.storage.auth-token-life-hours}")
    private int authTokenLife;

    @Transactional
    @Scheduled(fixedDelay = 30000)
    public void cleanupExpiredTokens() {
        LocalDateTime now = LocalDateTime.now();

        List<AuthToken> expiredTokens = authTokenRepository.findByExpiresAtBefore(now);

        if (!expiredTokens.isEmpty()) {
            authTokenRepository.deleteAll(expiredTokens);
        }
    }
}
