package com.davos.assessment.audit;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class AuditRetentionJob {
  private final AuditLogRepository auditLogRepository;
  private final int retentionDays;

  public AuditRetentionJob(
      AuditLogRepository auditLogRepository,
      @Value("${app.audit.retention-days:365}") int retentionDays) {
    this.auditLogRepository = auditLogRepository;
    this.retentionDays = retentionDays;
  }

  @Scheduled(cron = "${app.audit.retention-cron:0 20 3 * * *}")
  @Transactional
  public void cleanup() {
    Instant cutoff = Instant.now().minus(retentionDays, ChronoUnit.DAYS);
    auditLogRepository.deleteByCreatedAtBefore(cutoff);
  }
}
