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

import static com.iqser.red.service.persistence.management.v1.processor.roles.ActionRoles.SEARCH_AUDIT_LOG;
import static com.knecon.fforesight.databasetenantcommons.providers.utils.MagicConverter.convert;

import java.util.List;

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.persistence.AuditPersistenceService;
import com.iqser.red.service.persistence.service.v1.api.external.resource.AuditResource;
import com.iqser.red.service.persistence.service.v1.api.shared.model.AuditCategory;
import com.iqser.red.service.persistence.service.v1.api.shared.model.AuditResponse;
import com.iqser.red.service.persistence.service.v1.api.shared.model.audit.AuditModel;
import com.iqser.red.service.persistence.service.v1.api.shared.model.audit.AuditRequest;
import com.iqser.red.service.persistence.service.v1.api.shared.model.audit.AuditSearchRequest;
import com.iqser.red.service.persistence.service.v1.api.shared.model.audit.CategoryModel;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequiredArgsConstructor
public class AuditController implements AuditResource {

    private final AuditPersistenceService auditPersistenceService;


    @Override
    @PreAuthorize("hasAuthority('" + SEARCH_AUDIT_LOG + "')")
    public AuditResponse searchAuditLog(@RequestBody AuditSearchRequest auditSearchRequest) {

        var auditModels = convert(auditPersistenceService.search(auditSearchRequest), AuditModel.class);
        auditPersistenceService.insertRecord(AuditRequest.builder()
                .userId(KeycloakSecurity.getUserId())
                .objectId(auditSearchRequest.getObjectId())
                .category(AuditCategory.AUDIT.name())
                .message("Audit Log has been viewed.")
                .build());

        return new AuditResponse(auditModels.getElements(), auditModels.getTotalHits(), auditModels.getPage(), auditModels.getPageSize());
    }


    @Override
    @PreAuthorize("hasAuthority('" + SEARCH_AUDIT_LOG + "')")
    public List<CategoryModel> getAuditCategories() {

        return auditPersistenceService.getCategories();
    }

}
