package com.r11.tools.configuration;

import com.r11.tools.repository.MockedResponseRepository;
import com.r11.tools.repository.RequestHistoryRepository;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;

/**
 * Based on configuration deletes all outdated messages and history records from database.
 *
 * @author Mikołaj Widła
 */

@EnableScheduling
@EnableAsync
@Configuration
public class RetentionConfiguration {

    private final MockedResponseRepository responseRepository;
    private final RequestHistoryRepository historyRepository;
    private final RetentionConfigurationProperties retentionProperties;
    private final Logger log = LogManager.getRootLogger();


    public RetentionConfiguration(MockedResponseRepository responseRepository,
                                  RequestHistoryRepository historyRepository,
                                  RetentionConfigurationProperties retentionProperties){
        this.historyRepository = historyRepository;
        this.responseRepository = responseRepository;
        this.retentionProperties = retentionProperties;
    }
    @Scheduled(fixedDelayString = "#{${retention.retention-cooldown} * 60000 }")
    @Async
    public void deleteMessagesAndHistoryRecords(){
        log.info("OUTDATED MESSAGES AND HISTORY RECORDS DELETED!");
        responseRepository
                .findAll()
                .iterator()
                .forEachRemaining( mockedMessage -> {
                    if (mockedMessage.getCreatedAt().plusMinutes(retentionProperties.getMinutesToDeleteMessage()).isBefore(LocalDateTime.now())){
                        responseRepository.delete(mockedMessage);
                    }
                } );

        historyRepository
                .findAll()
                .iterator()
                .forEachRemaining(
                        historyRecord -> {
                            if (historyRecord.getDateTimeStamp().plusMinutes(retentionProperties.getMinutesToDeleteHistoryRecord()).isBefore(LocalDateTime.now())){
                                historyRepository.delete(historyRecord);
                            }
                        }
                );
    }

}
