<?php

namespace App\Repository\ContentVersion;

use App\Entity\ContentVersion;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;

final class DoctrineContentVersionRepository extends ServiceEntityRepository implements ContentVersionRepositoryInterface
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, ContentVersion::class);
    }

    public function findById(int $contentVersionId): ?ContentVersion
    {
        return $this->findOneBy(['id' => $contentVersionId]);
    }

    /**
     * @param ContentVersion $contentVersion
     *
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function save(ContentVersion $contentVersion): void
    {
        $this->_em->persist($contentVersion);
        $this->_em->flush();
    }

    /**
     * @param ContentVersion $contentVersion
     *
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function delete(ContentVersion $contentVersion): void
    {
        $this->_em->remove($contentVersion);
        $this->_em->flush();
    }

    public function moveVersionsBetweenUsers(int $from, int $to)
    {
        $qb = $this->createQueryBuilder('cv');
        $qb
            ->update()
            ->set('cv.createdBy', $to)
            ->where('cv.createdBy = :from');

        $qb->setParameter('from', $from);

        return $qb->getQuery()->execute();
    }
}
