package at.procon.ted.event;

import at.procon.ted.config.TedProcessorProperties;
import at.procon.dip.runtime.condition.ConditionalOnRuntimeMode;
import at.procon.dip.runtime.config.RuntimeMode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.ProducerTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * Event listener that triggers vectorization after document save transaction commits.
 * This ensures the document is visible in the database before vectorization starts.
 *
 * @author Martin.Schweitzer@procon.co.at and claude.ai
 */
@Component
@ConditionalOnRuntimeMode(RuntimeMode.LEGACY)
@RequiredArgsConstructor
@Slf4j
public class VectorizationEventListener {

    private final ProducerTemplate producerTemplate;
    private final TedProcessorProperties properties;

    /**
     * Triggered AFTER the transaction commits (document is now visible in DB).
     * Queues the document for async vectorization.
     */
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void onDocumentSaved(DocumentSavedEvent event) {
        if (!properties.getVectorization().isEnabled()) {
            return;
        }

        try {
            log.debug("Document saved event received, triggering vectorization for: {}", event.documentId());
            producerTemplate.sendBodyAndHeader("direct:vectorize", null, "documentId", event.documentId());
            log.debug("Vectorization queued for document: {} (publication: {})",
                    event.documentId(), event.publicationId());
        } catch (Exception e) {
            log.warn("Failed to queue document {} for vectorization: {}",
                    event.documentId(), e.getMessage());
            // Non-critical: scheduler will pick it up later
        }
    }
}
