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

import static com.iqser.red.service.persistence.management.v1.processor.roles.ActionRoles.READ_LICENSE;
import static com.iqser.red.service.persistence.management.v1.processor.service.LicenseUtilityService.LICENSE_OBJECT_ID;

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

import com.iqser.red.service.persistence.management.v1.processor.service.LicenseUtilityService;
import com.iqser.red.service.persistence.service.v1.api.internal.resources.LicenseResource;
import com.iqser.red.service.persistence.service.v1.api.shared.model.license.RedactionLicenseModel;
import com.iqser.red.storage.commons.service.StorageService;
import com.knecon.fforesight.tenantcommons.TenantContext;

import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
public class LicenseInternalController implements LicenseResource {

    private final StorageService storageService;
    private final LicenseUtilityService licenseUtilityService;


    @Override
    public RedactionLicenseModel getLicense() {

        String tenantId = TenantContext.getTenantId();
        if (storageService.objectExists(tenantId, LICENSE_OBJECT_ID)) {
            try {
                return storageService.readJSONObject(tenantId, LICENSE_OBJECT_ID, RedactionLicenseModel.class);
            } catch (Exception e) {
                return licenseUtilityService.generateDemoLicense();
            }
        } else {
            return licenseUtilityService.generateDemoLicense();
        }
    }

}
