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_REPORT;

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

import com.knecon.fforesight.keycloakcommons.security.KeycloakSecurity;
import com.iqser.red.service.persistence.management.v1.processor.service.LicenseReportService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.AuditPersistenceService;
import com.iqser.red.service.persistence.service.v1.api.external.resource.LicenseReportResource;
import com.iqser.red.service.persistence.service.v1.api.shared.model.AuditCategory;
import com.iqser.red.service.persistence.service.v1.api.shared.model.audit.AuditRequest;
import com.iqser.red.service.persistence.service.v1.api.shared.model.license.LicenseReport;
import com.iqser.red.service.persistence.service.v1.api.shared.model.license.LicenseReportRequest;

import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
public class LicenseReportController implements LicenseReportResource {

    private static final String LICENSE_AUDIT_KEY = "License";
    private final AuditPersistenceService auditPersistenceService;

    private final LicenseReportService licenseReportService;


    @Override
    @PreAuthorize("hasAuthority('" + READ_LICENSE_REPORT + "')")
    public LicenseReport getReport(@RequestBody LicenseReportRequest reportRequest) {

        LicenseReport licenseReport = licenseReportService.getLicenseReport(reportRequest);
        auditPersistenceService.audit(AuditRequest.builder()
                .userId(KeycloakSecurity.getUserId())
                .objectId(LICENSE_AUDIT_KEY)
                .category(AuditCategory.LICENSE.name())
                .message("License report has been viewed.")
                .build());
        return licenseReport;
    }

}
