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.NotFoundException;
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) {

        var rulesOptional = rulesPersistenceService.getRules(dossierTemplateId, ruleFileType);
        if (rulesOptional.isEmpty()) {
            throw new NotFoundException(String.format("No rule file of type %s found for dossierTemplateId %s", ruleFileType, dossierTemplateId));
        }
        return new JSONPrimitive<>(rulesOptional.get().getValue());
    }


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

        var rulesOptional = rulesPersistenceService.getRules(dossierTemplateId, ruleFileType);
        if (rulesOptional.isEmpty()) {
            throw new NotFoundException(String.format("No rule file of type %s found for dossierTemplateId %s", ruleFileType, dossierTemplateId));
        }

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

        return rulesOptional.get().getVersion();
    }


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

        rulesPersistenceService.setTimeoutDetected(dossierTemplateId, ruleFileType);
    }

}
