package com.pressing.modules.audit;

import com.pressing.domain.audit.AuditLog;
import com.pressing.domain.audit.AuditLogRepository;
import com.pressing.tenant.TenantContext;
import java.time.LocalDateTime;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AuditService {

    private final AuditLogRepository repository;

    public AuditService(AuditLogRepository repository) {
        this.repository = repository;
    }

    @Transactional
    public void log(String action, String details, String entityType, Long entityId) {
        Long siteId = TenantContext.getSiteId();
        if (siteId == null) {
            return;
        }
        AuditLog log = new AuditLog();
        log.setSiteId(siteId);
        log.setEventDateTime(LocalDateTime.now());
        log.setAction(action);
        log.setDetails(details);
        log.setOperatorName(TenantContext.getUsername() != null ? TenantContext.getUsername() : "system");
        log.setOperatorId(TenantContext.getUsername());
        log.setEntityType(entityType);
        log.setEntityId(entityId);
        repository.save(log);
    }
}
