package com.atlassian.bitbucket.ssh;

import com.atlassian.bitbucket.audit.AuditEntry;
import com.atlassian.bitbucket.audit.AuditEntryBuilder;
import com.atlassian.bitbucket.ssh.event.SshKeyCreatedEvent;
import com.atlassian.bitbucket.ssh.event.SshKeyEventConverter;
import com.atlassian.bitbucket.user.ApplicationUser;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static com.atlassian.bitbucket.JsonTestUtils.assertJsonContains;
import static com.atlassian.bitbucket.JsonTestUtils.assertJsonNotContains;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class SshKeyEventConverterTest {

    private final AuditEntryBuilder builder = new AuditEntryBuilder();
    private final SshKeyEventConverter converter = new SshKeyEventConverter();

    @Mock
    private SshKey key;
    @Mock
    private ApplicationUser user;

    @Before
    public void setup() {
        when(key.getId()).thenReturn(1);
        when(key.getLabel()).thenReturn("key-label");
        when(key.getText()).thenReturn("key-text");

        when(user.getId()).thenReturn(2);
        when(user.getSlug()).thenReturn("user-slug");
        when(user.getName()).thenReturn("user-name");
    }

    @Test
    public void testResourceKeyCreated() {
        AuditEntry entry = converter.convert(new SshKeyCreatedEvent(this, key), builder);

        assertEquals(SshKeyCreatedEvent.class.getSimpleName(), entry.getAction());
        assertEquals("Global", entry.getTarget());
        String details = entry.getDetails();

        assertJsonContains(details, "id", "1");
        assertJsonContains(details, "public-key", "key-text");
        assertJsonContains(details, "label", "key-label");
        assertJsonNotContains(details, "user");
    }

    @Test
    public void testUserKeyCreated() {
        when(key.getUser()).thenReturn(user);
        AuditEntry entry = converter.convert(new SshKeyCreatedEvent(this, key), builder);

        assertEquals(SshKeyCreatedEvent.class.getSimpleName(), entry.getAction());
        assertEquals("user-slug", entry.getTarget());
        String details = entry.getDetails();

        assertJsonContains(details, "id", "1");
        assertJsonContains(details, "public-key", "key-text");
        assertJsonContains(details, "label", "key-label");
        assertJsonContains(details, "user.id", "2");
        assertJsonContains(details, "user.name", "user-name");
        assertJsonContains(details, "user.slug", "user-slug");
    }
}
