package com.iqser.red.persistence.service.v1.external.api.impl.controller;

import static com.iqser.red.service.persistence.management.v1.processor.roles.ActionRoles.READ_VERSIONS;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.iqser.red.service.persistence.management.v1.processor.service.persistence.DictionaryPersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.RulesPersistenceService;
import com.iqser.red.service.persistence.service.v1.api.external.resource.VersionsResource;
import com.iqser.red.service.persistence.service.v1.api.shared.model.RuleFileType;
import com.iqser.red.service.persistence.service.v1.api.shared.model.VersionsResponse;

import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
public class VersionsController implements VersionsResource {

    private final DictionaryPersistenceService dictionaryPersistenceService;
    private final RulesPersistenceService rulesPersistenceService;


    @Override
    @PreAuthorize("hasAuthority('" + READ_VERSIONS + "')")
    public Map<String, VersionsResponse> getVersions(@RequestParam(DOSSIER_TEMPLATE_PARAMETER_NAME) List<String> dossierTemplateIds) {

        var result = new HashMap<String, VersionsResponse>();
        dossierTemplateIds.forEach(rsId -> {
            VersionsResponse response = new VersionsResponse(dictionaryPersistenceService.getVersion(rsId), rulesPersistenceService.getVersion(rsId, RuleFileType.ENTITY));
            result.put(rsId, response);
        });

        return result;
    }


    @Override
    @PreAuthorize("hasAuthority('" + READ_VERSIONS + "')")
    public Long getDossierDictionaryVersion(@PathVariable(DOSSIER_TEMPLATE_PARAMETER_NAME) String dossierTemplateId, @PathVariable(DOSSIER_ID_PARAM) String dossierId) {

        return dictionaryPersistenceService.getVersionForDossier(dossierId);
    }

}
