package com.atlassian.bitbucket.internal.mirroring.upstream;

import com.atlassian.bitbucket.audit.AuditEntry;
import com.atlassian.bitbucket.audit.AuditEntryBuilder;
import com.atlassian.bitbucket.audit.AuditEntryConverter;
import com.atlassian.bitbucket.event.ApplicationEvent;
import com.atlassian.bitbucket.util.AuditUtils;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

public abstract class BaseMirroringEventConverter<T> implements AuditEntryConverter<T> {
    protected AuditEntry convert(@Nonnull ApplicationEvent event, AuditEntryBuilder builder, Map<String, Object> payload) {
        try {
            return builder
                    .action(event.getClass())
                    .timestamp(new Date())
                    .details(AuditUtils.toJSONString(payload))
                    .user(event.getUser())
                    .target("com.atlassian.bitbucket.server.bitbucket-mirroring")
                    .build();
        } catch (IOException e) {
            throw new RuntimeException(String.format("Failed to convert %s to JSON", payload), e);
        }
    }
}
