package com.iqser.red.service.persistence.management.v1.processor.service.job;

import java.time.OffsetDateTime;
import java.util.List;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.management.v1.processor.entity.dossier.FileEntity;
import com.iqser.red.service.persistence.management.v1.processor.service.ApplicationConfigService;
import com.iqser.red.service.persistence.management.v1.processor.service.FileDeletionService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository.FileRepository;
import com.iqser.red.service.persistence.management.v1.processor.utils.TenantUtils;
import com.knecon.fforesight.tenantcommons.TenantContext;
import com.knecon.fforesight.tenantcommons.TenantProvider;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
@Service
@DisallowConcurrentExecution
public class DeletedFilesCleanupJob implements Job {

    private final FileRepository fileRepository;
    private final FileDeletionService fileDeletionService;
    private final ApplicationConfigService applicationConfigService;
    private final TenantProvider tenantProvider;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {

        tenantProvider.getTenants().forEach(tenant -> {

            if (!TenantUtils.isTenantReadyForPersistence(tenant)) {
                return;
            }

            TenantContext.setTenantId(tenant.getTenantId());

            var now = OffsetDateTime.now();
            var applicationConfigurationEntity = applicationConfigService.getApplicationConfig();

            // Directly query the files that need hard deletion
            List<FileEntity> filesToDelete = fileRepository.findFilesHardDeletedTimeAfter(
                    now.minusHours(applicationConfigurationEntity.getHardDeleteCleanupRetryTime()));

            for (var file : filesToDelete) {
                fileDeletionService.hardDeleteFileDataAndIndexUpdates(file.getDossierId(), file.getId());
                log.info("Deleted file data and index updates for dossier id {} and file id {}", file.getDossierId(), file.getId());
            }
        });
    }


}
