package at.procon.dip.testsupport;

import at.procon.dip.testsupport.SearchTestDataFactory.CreatedDocument;
import at.procon.dip.domain.document.DocumentFamily;
import at.procon.dip.domain.document.DocumentType;
import at.procon.dip.domain.document.RepresentationType;
import at.procon.dip.embedding.service.RepresentationEmbeddingOrchestrator;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@RequiredArgsConstructor
@Transactional
public class SemanticSearchTestDataFactory {

    private final SearchTestDataFactory lexicalFactory;
    private final RepresentationEmbeddingOrchestrator embeddingOrchestrator;

    public CreatedDocument createAndEmbedPrimaryRepresentation(
            String title,
            String summary,
            String body,
            DocumentType documentType,
            DocumentFamily documentFamily,
            String languageCode,
            RepresentationType primaryType,
            String modelKey) {

        CreatedDocument created = lexicalFactory.createDocumentWithPrimaryRepresentation(
                title,
                summary,
                body,
                documentType,
                documentFamily,
                languageCode,
                primaryType
        );
        embedDocument(created.document().getId(), modelKey);
        return created;
    }

    public CreatedDocument createAndEmbedPrimaryAndChunks(
            String title,
            String summary,
            String primaryBody,
            String languageCode,
            List<String> chunkBodies,
            String modelKey) {
        CreatedDocument created = lexicalFactory.createDocumentWithPrimaryAndChunks(
                title,
                summary,
                primaryBody,
                languageCode,
                chunkBodies
        );
        embedDocument(created.document().getId(), modelKey);
        return created;
    }

    private void embedDocument(java.util.UUID documentId, String modelKey) {
        embeddingOrchestrator.enqueueDocument(documentId, modelKey);
        while (embeddingOrchestrator.processNextReadyBatch() > 0) {
            // drain the ready queue synchronously for deterministic tests
        }
    }
}
