package dev.lions.user.manager.service.impl;

import dev.lions.user.manager.dto.audit.AuditLogDTO;
import dev.lions.user.manager.enums.audit.TypeActionAudit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;

class AuditServiceImplTest {

    AuditServiceImpl auditService;

    @BeforeEach
    void setUp() {
        auditService = new AuditServiceImpl();
        auditService.auditEnabled = true; // manually injecting config property
        auditService.logToDatabase = false;
    }

    @Test
    void testLogAction() {
        AuditLogDTO log = new AuditLogDTO();
        log.setTypeAction(TypeActionAudit.USER_CREATE);
        log.setActeurUsername("admin");

        auditService.logAction(log);

        assertEquals(1, auditService.getTotalCount());
        assertNotNull(log.getId());
        assertNotNull(log.getDateAction());
    }

    @Test
    void testLogDisabled() {
        auditService.auditEnabled = false;
        AuditLogDTO log = new AuditLogDTO();

        auditService.logAction(log);
        assertEquals(0, auditService.getTotalCount());
    }

    @Test
    void testLogSuccess() {
        auditService.logSuccess(TypeActionAudit.USER_CREATE, "USER", "1", "user", "realm", "admin", "desc");
        assertEquals(1, auditService.getTotalCount());
    }

    @Test
    void testLogFailure() {
        auditService.logFailure(TypeActionAudit.USER_CREATE, "USER", "1", "user", "realm", "admin", "ERR", "Error");
        assertEquals(1, auditService.getTotalCount());
        List<AuditLogDTO> failures = auditService.findFailures("realm", null, null, 0, 10);
        assertEquals(1, failures.size());
    }

    @Test
    void testSearchLogs() {
        auditService.logSuccess(TypeActionAudit.USER_CREATE, "USER", "1", "user1", "realm", "admin1", "");
        auditService.logSuccess(TypeActionAudit.USER_UPDATE, "USER", "1", "user1", "realm", "admin1", "");
        auditService.logSuccess(TypeActionAudit.ROLE_CREATE, "ROLE", "r", "role", "realm", "admin2", "");

        List<AuditLogDTO> byActeur = auditService.findByActeur("admin1", null, null, 0, 10);
        assertEquals(2, byActeur.size());

        List<AuditLogDTO> byType = auditService.findByTypeAction(TypeActionAudit.ROLE_CREATE, "realm", null, null, 0,
                10);
        assertEquals(1, byType.size());
    }

    @Test
    void testClearAll() {
        auditService.logAction(new AuditLogDTO());
        auditService.clearAll();
        assertEquals(0, auditService.getTotalCount());
    }
}
