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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.CurrentApplicationTypeProvider;
import com.iqser.red.service.persistence.management.v1.processor.service.FileStatusService;
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.service.v1.api.shared.model.dossiertemplate.dossier.file.WorkflowStatus;

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

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

    private static final String NAME = "Reanalyse layout for not approved Documine files";
    private static final long VERSION = 20;

    @Autowired
    private FileStatusService fileStatusService;

    @Autowired
    private DossierPersistenceService dossierPersistenceService;

    @Autowired
    private FileStatusPersistenceService fileStatusPersistenceService;

    @Autowired
    private CurrentApplicationTypeProvider currentApplicationTypeProvider;


    public V20DocumineLayoutRewriteMigration() {

        super(NAME, VERSION);
    }


    @Override
    protected void migrate() {

        if (!currentApplicationTypeProvider.isDocuMine()) {
            log.info("Skipping DocumineLayoutRewriteMigration20 as application type is not DocuMine!!!");
            return;
        }

        var dossiers = dossierPersistenceService.findAllDossiers();
        dossiers.forEach(dossier -> {
            if (dossier.getHardDeletedTime() == null) {
                var files = fileStatusPersistenceService.getStatusesForDossier(dossier.getId());
                log.info("Start migration of dossier {}", dossier.getId());
                files.forEach(file -> {
                    if (file.getHardDeletedTime() == null && !file.getWorkflowStatus().equals(WorkflowStatus.APPROVED)) {
                        log.info("Set full reanalyse for file {}", file.getId());
                        fileStatusService.setStatusFullReprocess(dossier.getId(), file.getId(), false, true, false);
                        log.info("Finished migration of file {}", file.getId());
                    }
                });
                log.info("Finished migration of dossier {}", dossier.getId());
            }
        });

    }

}
