package com.iqser.red.service.persistence.v1.internal.api.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.iqser.red.service.persistence.management.v1.processor.exception.RulesTimeoutDetectedException;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.RulesPersistenceService;
import com.iqser.red.service.persistence.service.v1.api.internal.resources.RulesResource;
import com.iqser.red.service.persistence.service.v1.api.shared.model.RuleFileType;
import com.iqser.red.service.persistence.service.v1.api.shared.model.common.JSONPrimitive;

import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
public class RulesInternalController implements RulesResource {

    private final RulesPersistenceService rulesPersistenceService;


    @Override
    public JSONPrimitive<String> getRules(@PathVariable(DOSSIER_TEMPLATE_PARAMETER_NAME) String dossierTemplateId,
                                          @PathVariable(RULE_FILE_TYPE_PARAMETER_NAME) RuleFileType ruleFileType) {

        return new JSONPrimitive<>(rulesPersistenceService.getRules(dossierTemplateId, ruleFileType).getValue());
    }


    @Override
    public long getVersion(@PathVariable(DOSSIER_TEMPLATE_PARAMETER_NAME) String dossierTemplateId, @PathVariable(RULE_FILE_TYPE_PARAMETER_NAME) RuleFileType ruleFileType) {

        var rules = rulesPersistenceService.getRules(dossierTemplateId, ruleFileType);

        if (rules.isTimeoutDetected()) {
            throw new RulesTimeoutDetectedException(dossierTemplateId);
        }

        return rules.getVersion();
    }


    @Override
    public void setRulesTimeoutDetected(@PathVariable(DOSSIER_TEMPLATE_PARAMETER_NAME) String dossierTemplateId,
                                        @PathVariable(RULE_FILE_TYPE_PARAMETER_NAME) RuleFileType ruleFileType) {

        rulesPersistenceService.setTimeoutDetected(dossierTemplateId, ruleFileType);
    }

}
