package com.iqser.red.service.persistence.management.v1.processor.migration.migrations;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.management.v1.processor.migration.Migration;
import com.iqser.red.service.persistence.management.v1.processor.service.manualredactions.ManualRedactionService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.DossierPersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.FileStatusPersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.annotations.AddRedactionPersistenceService;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Setter
@Service
public class RemoveFalsePositiveManualRedactions6 extends Migration {

    private static final String NAME = "Remove false positives manual redactions";
    private static final long VERSION = 6;

    @Autowired
    private DossierPersistenceService dossierPersistenceService;

    @Autowired
    private FileStatusPersistenceService fileStatusPersistenceService;

    @Autowired
    private ManualRedactionService manualRedactionService;

    @Autowired
    private AddRedactionPersistenceService addRedactionPersistenceService;


    public RemoveFalsePositiveManualRedactions6() {

        super(NAME, VERSION);
    }


    @Override
    protected void migrate() {

        var dossiers = dossierPersistenceService.findAllDossiers();
        dossiers.forEach(dossier -> {
            var files = fileStatusPersistenceService.getStatusesForDossier(dossier.getId());
            files.forEach(file -> {
                if (file.getHardDeletedTime() == null) {
                    var annotationIdsToRemove = new ArrayList<String>();
                    var manualRedactions = manualRedactionService.getManualRedactions( file.getId());

                    if (manualRedactions != null && manualRedactions.getEntriesToAdd() != null) {
                        manualRedactions.getEntriesToAdd().forEach(addRedaction -> {
                            if (addRedaction.getType().contains("false_positive")) {
                                annotationIdsToRemove.add(addRedaction.getAnnotationId());
                            }
                        });
                    }

                    log.info("Hard deleting false positive annotations for file: {} / {}", file.getId(), annotationIdsToRemove);

                    if (!annotationIdsToRemove.isEmpty()) {
                        annotationIdsToRemove.forEach(id -> addRedactionPersistenceService.hardDelete(file.getId(), id));
                    }
                }
            });
        });
    }

}





