package org.raddatz.familienarchiv.geschichte.journeyitem;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.raddatz.familienarchiv.document.DocumentDeletingEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Slf4j
class JourneyItemDocumentDeleteListener {

    private final JourneyItemRepository journeyItemRepository;

    /**
     * Plain @EventListener — runs synchronously in the publisher's thread and transaction.
     * Load-bearing choice: AFTER_COMMIT would fire after the FK ON DELETE SET NULL has
     * already 500'd; @Async would run outside the delete transaction (breaks AC-5 rollback).
     * See ADR-038. DocumentService cannot call JourneyItemService directly because
     * Spring Framework 7 prohibits the resulting constructor-injection cycle.
     */
    @EventListener
    void onDocumentDeleting(DocumentDeletingEvent event) {
        int deleted = journeyItemRepository.deleteNoteLessByDocumentId(event.documentId());
        if (deleted > 0) {
            log.warn("Cascade-deleted {} note-less journey item(s) for document {}", deleted, event.documentId());
        }
    }
}
