<?php

/**
 * Copyright (c) 2026 PrestaShop SA
 *
 * This file is part of the PrestaShop AskAI solution.
 * For license terms, see LICENSE.md in this module.
 */

declare(strict_types=1);

namespace PrestaShop\Module\PsAskAi\Repository;

use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use PrestaShop\Module\PsAskAi\Entity\PsAskAiConversation;

/**
 * @extends ServiceEntityRepository<PsAskAiConversation>
 *
 * @method PsAskAiConversation|null find($id, $lockMode = null, $lockVersion = null)
 * @method PsAskAiConversation|null findOneBy(array $criteria, array $orderBy = null)
 * @method PsAskAiConversation[] findAll()
 * @method PsAskAiConversation[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class PsAskAiConversationRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, PsAskAiConversation::class);
    }

    public function findOneByThreadId(string $threadId): ?PsAskAiConversation
    {
        return $this->findOneBy(['threadId' => $threadId]);
    }

    /**
     * @return PsAskAiConversation[]
     */
    public function findActiveByEmployee(int $idEmployee, int $idShop): array
    {
        return $this->createQueryBuilder('c')
            ->where('c.idEmployee = :idEmployee')
            ->andWhere('c.idShop = :idShop')
            ->andWhere('c.archivedAt IS NULL')
            ->setParameter('idEmployee', $idEmployee)
            ->setParameter('idShop', $idShop)
            ->orderBy('c.updatedAt', 'DESC')
            ->getQuery()
            ->getResult();
    }

    public function save(PsAskAiConversation $conversation, bool $flush = true): void
    {
        $this->getEntityManager()->persist($conversation);
        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }
}
