package at.procon.dip.domain.document.repository;

import at.procon.dip.domain.document.RepresentationType;
import at.procon.dip.domain.document.DocumentType;
import at.procon.dip.domain.document.EmbeddingStatus;
import at.procon.dip.domain.document.entity.DocumentTextRepresentation;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface DocumentTextRepresentationRepository extends JpaRepository<DocumentTextRepresentation, UUID> {

    List<DocumentTextRepresentation> findByDocument_Id(UUID documentId);

    List<DocumentTextRepresentation> findByDocument_IdAndRepresentationType(UUID documentId, RepresentationType representationType);

    List<DocumentTextRepresentation> findByPrimaryRepresentationTrue();

    long countByPrimaryRepresentationTrue();

    long countByRepresentationType(RepresentationType representationType);

    Optional<DocumentTextRepresentation> findFirstByDocument_IdAndPrimaryRepresentationTrue(UUID documentId);

    @Query("""
            SELECT r
            FROM DocumentTextRepresentation r
            JOIN r.document d
            WHERE (:documentType IS NULL OR d.documentType = :documentType)
              AND (:representationType IS NULL OR r.representationType = :representationType)
              AND (:builderKey IS NULL OR r.builderKey = :builderKey)
              AND (:primaryOnly = false OR r.primaryRepresentation = true)
              AND r.textBody IS NOT NULL
              AND r.textBody <> ''
              AND (:includeCompleted = true OR NOT EXISTS (
                    SELECT e.id
                    FROM DocumentEmbedding e
                    WHERE e.representation.id = r.id
                      AND e.model.modelKey = :modelKey
                      AND e.embeddingStatus = :completedStatus
              ))
            ORDER BY r.createdAt ASC, r.id ASC
            """)
    List<DocumentTextRepresentation> findEmbeddingCandidatesByDocumentType(
            @Param("documentType") DocumentType documentType,
            @Param("representationType") RepresentationType representationType,
            @Param("builderKey") String builderKey,
            @Param("primaryOnly") boolean primaryOnly,
            @Param("modelKey") String modelKey,
            @Param("completedStatus") EmbeddingStatus completedStatus,
            @Param("includeCompleted") boolean includeCompleted,
            Pageable pageable);
}
