<?php

declare(strict_types=1);

namespace App\Module\Mail\Infrastructure\Doctrine;

use App\Module\Mail\Domain\Entity\MailMessage;
use App\Module\Mail\Domain\Entity\TaskMailLink;
use App\Module\Mail\Domain\Repository\TaskMailLinkRepositoryInterface;
use App\Shared\Domain\Contract\TaskInterface;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @extends ServiceEntityRepository<TaskMailLink>
 */
class DoctrineTaskMailLinkRepository extends ServiceEntityRepository implements TaskMailLinkRepositoryInterface
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, TaskMailLink::class);
    }

    /**
     * @return list<TaskMailLink>
     */
    public function findByTask(TaskInterface $task): array
    {
        return $this->createQueryBuilder('l')
            ->andWhere('l.task = :task')
            ->setParameter('task', $task)
            ->orderBy('l.linkedAt', 'DESC')
            ->getQuery()
            ->getResult()
        ;
    }

    public function findByTaskAndMessage(TaskInterface $task, MailMessage $message): ?TaskMailLink
    {
        return $this->findOneBy(['task' => $task, 'mailMessage' => $message]);
    }

    /**
     * @return list<TaskMailLink>
     */
    public function findByMessage(MailMessage $message): array
    {
        return $this->findBy(['mailMessage' => $message]);
    }
}
