package dev.lions.unionflow.server.repository;

import dev.lions.unionflow.server.entity.Conversation;
import dev.lions.unionflow.server.entity.Membre;
import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase;
import jakarta.enterprise.context.ApplicationScoped;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * Repository pour Conversation
 *
 * @author UnionFlow Team
 * @version 1.0
 * @since 2026-03-16
 */
@ApplicationScoped
public class ConversationRepository implements PanacheRepositoryBase<Conversation, UUID> {

    /**
     * Trouve toutes les conversations d'un membre
     */
    public List<Conversation> findByParticipant(UUID membreId, boolean includeArchived) {
        String query = """
            SELECT DISTINCT c FROM Conversation c
            JOIN c.participants p
            WHERE p.id = :membreId
            AND (c.actif IS NULL OR c.actif = true)
            """;

        if (!includeArchived) {
            query += " AND c.isArchived = false";
        }

        query += " ORDER BY c.updatedAt DESC NULLS LAST, c.dateCreation DESC";

        return getEntityManager()
            .createQuery(query, Conversation.class)
            .setParameter("membreId", membreId)
            .getResultList();
    }

    /**
     * Trouve une conversation par ID et vérifie que le membre en fait partie
     */
    public Optional<Conversation> findByIdAndParticipant(UUID conversationId, UUID membreId) {
        String query = """
            SELECT DISTINCT c FROM Conversation c
            JOIN c.participants p
            WHERE c.id = :conversationId
            AND p.id = :membreId
            AND (c.actif IS NULL OR c.actif = true)
            """;

        return getEntityManager()
            .createQuery(query, Conversation.class)
            .setParameter("conversationId", conversationId)
            .setParameter("membreId", membreId)
            .getResultStream()
            .findFirst();
    }

    /**
     * Trouve les conversations d'une organisation
     */
    public List<Conversation> findByOrganisation(UUID organisationId) {
        return find("organisation.id = ?1 AND (actif IS NULL OR actif = true) ORDER BY updatedAt DESC NULLS LAST", organisationId)
            .list();
    }
}
