package com.iqser.red.service.peristence.v1.server.integration.tests;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.Map;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.iqser.red.service.peristence.v1.server.integration.client.AuditClient;
import com.iqser.red.service.peristence.v1.server.integration.service.UserProvider;
import com.iqser.red.service.peristence.v1.server.integration.utils.AbstractPersistenceServerServiceTest;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.AuditPersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository.AuditRepository;
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;

public class AuditTest extends AbstractPersistenceServerServiceTest {

    @Autowired
    private AuditClient auditClient;

    @Autowired
    private AuditPersistenceService auditPersistenceService;

    @Autowired
    private AuditRepository auditRepository;

    @Autowired
    private UserProvider userProvider;


    @Test
    public void testAudit() {

        var userId = userProvider.getUserId();

        auditPersistenceService.audit(AuditRequest.builder().category("c1").message("test").userId(userId).objectId("1").details(Map.of("key", "value")).build());
        auditPersistenceService.audit(AuditRequest.builder().category("c1").message("test").userId(userId).objectId("1").details(Map.of("key", "value")).build());
        auditPersistenceService.audit(AuditRequest.builder().category("c2").message("test").userId(userId).objectId("1").details(Map.of("key", "value")).build());

        assertThat(auditClient.getAuditCategories().size()).isGreaterThanOrEqualTo(2);
        assertThat(auditClient.getAuditCategories().stream().filter(c -> c.getCategory().equals("c1")).findAny().map(CategoryModel::getRecordCount).get()).isEqualTo(2);
        assertThat(auditClient.getAuditCategories().stream().filter(c -> c.getCategory().equals("c2")).findAny().map(CategoryModel::getRecordCount).get()).isEqualTo(1);

        var result = auditClient.searchAuditLog(AuditSearchRequest.builder().category("c1").page(0).pageSize(10).build());
        assertThat(result.getTotalHits()).isEqualTo(2);

        result = auditClient.searchAuditLog(AuditSearchRequest.builder().build());
        assertThat(result.getTotalHits()).isGreaterThanOrEqualTo(3);
        assertThat(auditClient.getAuditCategories()).isNotEmpty();
    }

}
