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

import java.util.List;
import java.util.Optional;

import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.management.v1.processor.entity.configuration.RuleSetEntity;
import com.iqser.red.service.persistence.management.v1.processor.entity.dossier.DossierTemplateEntity;
import com.iqser.red.service.persistence.management.v1.processor.migration.Migration;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.RulesPersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository.DossierTemplateRepository;
import com.iqser.red.service.persistence.service.v1.api.shared.model.RuleFileType;
import com.knecon.fforesight.tenantcommons.TenantContext;

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

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

    private final DossierTemplateRepository dossierTemplateRepository;
    private final RulesPersistenceService rulesPersistenceService;

    private static final String NAME = "Migration for rule files, updating imports after package change";
    private static final long VERSION = 26;


    public V26RuleFileUpdateMigration(DossierTemplateRepository dossierTemplateRepository, RulesPersistenceService rulesPersistenceService) {

        super(NAME, VERSION);
        this.dossierTemplateRepository = dossierTemplateRepository;
        this.rulesPersistenceService = rulesPersistenceService;
    }


    @Override
    protected void migrate() {

        log.info("Migration: Updating all rule files in all dossier templates");
        updateAllRuleFiles();

    }


    @SneakyThrows
    private void updateAllRuleFiles() {

        List<DossierTemplateEntity> dossierTemplates = dossierTemplateRepository.findAll();
        List<RuleSetEntity> ruleSets = dossierTemplates.stream()
                .map(dt -> rulesPersistenceService.getRules(dt.getId(), RuleFileType.ENTITY))
                .filter(Optional::isPresent)
                .map(Optional::get)
                .toList();

        String tenantId = TenantContext.getTenantId();
        ruleSets.parallelStream()
                .forEach(ruleSet -> {
                    TenantContext.setTenantId(tenantId);
                    String updatedRules = ruleSet.getValue()
                            .replaceAll("import com.knecon.fforesight.service.layoutparser.internal.api.data.redaction.LayoutEngine;",
                                        "import com.iqser.red.service.redaction.v1.server.model.document.nodes.LayoutEngine;");
                    rulesPersistenceService.setRules(updatedRules, ruleSet.getDossierTemplateId(), RuleFileType.ENTITY);
                });
    }

}
