<?php

namespace App\Repository;

use App\Entity\MediaObject;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    /**
     * Find media objects created by a specific user
     *
     * @param int $userId
     * @return MediaObject[]
     */
    public function findByUser(int $userId): array
    {
        return $this->createQueryBuilder('m')
            ->andWhere('m.createdBy = :userId')
            ->setParameter('userId', $userId)
            ->orderBy('m.createdAt', 'DESC')
            ->getQuery()
            ->getResult();
    }

    /**
     * Find recent media objects with limit
     *
     * @param int $limit
     * @return MediaObject[]
     */
    public function findRecent(int $limit = 10): array
    {
        return $this->createQueryBuilder('m')
            ->orderBy('m.createdAt', 'DESC')
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }

    /**
     * Save media object to database
     *
     * @param MediaObject $mediaObject
     * @param bool $flush Whether to immediately flush changes
     * @return void
     */
    public function save(MediaObject $mediaObject, bool $flush = true): void
    {
        $this->getEntityManager()->persist($mediaObject);

        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }

    /**
     * Remove media object from database
     *
     * @param MediaObject $mediaObject
     * @param bool $flush Whether to immediately flush changes
     * @return void
     */
    public function remove(MediaObject $mediaObject, bool $flush = true): void
    {
        $this->getEntityManager()->remove($mediaObject);

        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }
}