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

import jakarta.transaction.Transactional;

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.service.persistence.repository.RuleSetRepository;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
@SuppressWarnings("PMD.TooManyStaticImports")
public class RulesPersistenceService {

    public static final String DEFAULT_RULES = "" + "package drools\n" + "\n" + "import com.iqser.red.service.redaction.v1.server.redaction.model.Section\n" + "\n" + "global Section section\n" + "\n" + "// --------------------------------------- Your rules below this line--------------------------------------------------";

    private final RuleSetRepository ruleSetRepository;


    public RuleSetEntity getRules(String dossierTemplateId) {

        return ruleSetRepository.findById(dossierTemplateId).orElseGet(() -> {
            RuleSetEntity ruleSet = new RuleSetEntity();
            ruleSet.setDossierTemplateId(dossierTemplateId);
            ruleSet.setValue(DEFAULT_RULES);
            ruleSet.setVersion(1);

            return ruleSetRepository.save(ruleSet);
        });
    }


    @Transactional
    public void setRules(String rules, String dossierTemplateId) {

        ruleSetRepository.findById(dossierTemplateId).ifPresentOrElse(r -> {
            r.setValue(rules);
            r.setVersion(r.getVersion() + 1);
        }, () -> {
            RuleSetEntity ruleSet = new RuleSetEntity();
            ruleSet.setDossierTemplateId(dossierTemplateId);
            ruleSet.setValue(rules);
            ruleSet.setVersion(1);

            ruleSetRepository.save(ruleSet);
        });

    }

}
