package at.procon.dip.migration.repository;

import at.procon.dip.migration.service.LegacyTedEmbeddingTarget;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Query;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

@Repository
@RequiredArgsConstructor
public class LegacyTedEmbeddingTargetQueryRepository {

    private final EntityManager entityManager;

    @SuppressWarnings("unchecked")
    public List<LegacyTedEmbeddingTarget> findPrimarySemanticTargetsByLegacyIds(Collection<UUID> legacyIds) {
        if (legacyIds == null || legacyIds.isEmpty()) {
            return List.of();
        }

        Query query = entityManager.createNativeQuery("""
                SELECT p.legacy_procurement_document_id AS legacy_procurement_document_id,
                       p.document_id AS document_id,
                       r.id AS representation_id
                FROM ted.ted_notice_projection p
                JOIN doc.doc_text_representation r
                  ON r.document_id = p.document_id
                WHERE p.legacy_procurement_document_id IN (:legacyIds)
                  AND r.representation_type = 'SEMANTIC_TEXT'
                  AND COALESCE(r.is_primary, FALSE) = TRUE
                """);
        query.setParameter("legacyIds", legacyIds);

        List<Object[]> rows = query.getResultList();
        List<LegacyTedEmbeddingTarget> results = new ArrayList<>(rows.size());
        for (Object[] row : rows) {
            results.add(new LegacyTedEmbeddingTarget(
                    (UUID) row[0],
                    (UUID) row[1],
                    (UUID) row[2]
            ));
        }
        return results;
    }
}
