package com.davos.assessment.audit;

import com.davos.assessment.project.Project;
import com.davos.assessment.user.AppUser;
import com.davos.assessment.user.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AuditService {
  private static final Logger log = LoggerFactory.getLogger(AuditService.class);
  private final AuditLogRepository auditLogRepository;
  private final UserRepository userRepository;

  public AuditService(AuditLogRepository auditLogRepository, UserRepository userRepository) {
    this.auditLogRepository = auditLogRepository;
    this.userRepository = userRepository;
  }

  @Transactional(propagation = Propagation.REQUIRES_NEW)
  public void record(AppUser actor, String action, String targetType, String targetId) {
    record(null, actor, action, targetType, targetId);
  }

  @Transactional(propagation = Propagation.REQUIRES_NEW)
  public void record(Project project, AppUser actor, String action, String targetType, String targetId) {
    try {
      AuditLog entry = new AuditLog();
      AppUser persistedActor = actor;
      if (actor != null && actor.getId() != null && !userRepository.existsById(actor.getId())) {
        persistedActor = null;
      }
      entry.setActor(persistedActor);
      entry.setAction(action);
      entry.setTargetType(targetType);
      entry.setTargetId(targetId);
      entry.setProject(project);
      auditLogRepository.save(entry);
    } catch (RuntimeException ex) {
      log.warn("audit log write skipped: action={}, targetType={}, targetId={}, reason={}",
          action, targetType, targetId, ex.getMessage());
    }
  }
}
