package com.cameleer.server.app.admin;

import com.cameleer.server.core.admin.*;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;

import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

class AuditServiceTest {
    private AuditRepository mockRepository;
    private AuditService auditService;

    @BeforeEach
    void setUp() {
        mockRepository = mock(AuditRepository.class);
        auditService = new AuditService(mockRepository);
    }

    @Test
    void log_withExplicitUsername_insertsRecordWithCorrectFields() {
        var request = mock(HttpServletRequest.class);
        when(request.getRemoteAddr()).thenReturn("192.168.1.1");
        when(request.getHeader("User-Agent")).thenReturn("Mozilla/5.0");

        auditService.log("admin", "kill_query", AuditCategory.INFRA, "PID 42",
                Map.of("query", "SELECT 1"), AuditResult.SUCCESS, request);

        var captor = ArgumentCaptor.forClass(AuditRecord.class);
        verify(mockRepository).insert(captor.capture());
        var record = captor.getValue();
        assertEquals("admin", record.username());
        assertEquals("kill_query", record.action());
        assertEquals(AuditCategory.INFRA, record.category());
        assertEquals("PID 42", record.target());
        assertEquals("192.168.1.1", record.ipAddress());
        assertEquals("Mozilla/5.0", record.userAgent());
    }

    @Test
    void log_withNullRequest_handlesGracefully() {
        auditService.log("admin", "test", AuditCategory.CONFIG, null, null, AuditResult.SUCCESS, null);
        verify(mockRepository).insert(any(AuditRecord.class));
    }
}
