package com.atlassian.stash.internal.plugin.hooks.allapprovers;

import com.atlassian.bitbucket.audit.AuditEntry;
import com.atlassian.bitbucket.audit.AuditEntryBuilder;
import com.atlassian.bitbucket.audit.AuditEntryConverter;
import com.atlassian.bitbucket.util.AuditUtils;
import com.google.common.collect.Maps;

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

public class AllApproversMergeCheckChangedEventConverter implements AuditEntryConverter<AllApproversMergeCheckConfigChangedEvent> {

    @Nonnull
    @Override
    public AuditEntry convert(@Nonnull AllApproversMergeCheckConfigChangedEvent event, AuditEntryBuilder builder) {
        Map<String, Object> payload = Maps.newHashMap();
        payload.put("isEnabled", event.isEnabled());
        try {
            return builder
                    .action(event.getClass())
                    .timestamp(new Date())
                    .details(AuditUtils.toJSONString(payload))
                    .user(event.getUser())
                    .target(AuditUtils.toProjectAndRepositoryString(event.getRepository()))
                    .repository(event.getRepository())
                    .build();
        } catch (IOException e) {
            throw new RuntimeException(String.format("Failed to convert map %s to JSON", payload), e);
        }
    }
}
