package com.iqser.red.persistence.service.v1.external.api.impl.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.roles.ActionRoles.UPDATE_LICENSE;
import static com.iqser.red.service.persistence.management.v1.processor.service.LicenseUtilityService.*;

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

import com.iqser.red.service.persistence.management.v1.processor.service.FileFormatValidationService;
import com.iqser.red.service.persistence.management.v1.processor.service.LicenseUtilityService;
import com.iqser.red.service.persistence.service.v1.api.external.resource.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;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequiredArgsConstructor
public class LicenseController implements LicenseResource {

    private final StorageService storageService;
    private final LicenseUtilityService licenseUtilityService;
    private final FileFormatValidationService fileFormatValidationService;


    @Override
    @SneakyThrows
    @PreAuthorize("hasAuthority('" + UPDATE_LICENSE + "')")
    public void updateLicense(RedactionLicenseModel licenseModel) {

        storageService.storeJSONObject(TenantContext.getTenantId(), LICENSE_OBJECT_ID, licenseModel);
        fileFormatValidationService.evictValidFileFormatsForTenant(TenantContext.getTenantId());
    }


    @Override
    @PreAuthorize("hasAuthority('" + READ_LICENSE + "')")
    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();
        }
    }

}
