package com.mvrent.carrental.service;

import com.mvrent.carrental.model.AuditLog;
import com.mvrent.carrental.repository.AuditLogRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Persists a single audit row in its own transaction. Kept in a separate bean
 * so {@code REQUIRES_NEW} actually takes effect (not bypassed by self-invocation)
 * and a logging failure never rolls back the business operation.
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class AuditWriter {

    private final AuditLogRepository auditLogRepository;

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void write(AuditLog entry) {
        try {
            auditLogRepository.save(entry);
        } catch (Exception ex) {
            log.debug("Audit write skipped: {}", ex.getMessage());
        }
    }
}
