<?php

declare(strict_types=1);

namespace App\Repository;

use App\Entity\SharedImage;
use App\Entity\User;
use App\Enum\SharedImageStatus;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/** @extends ServiceEntityRepository<SharedImage> */
class SharedImageRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, SharedImage::class);
    }

    /**
     * @return array{items: SharedImage[], total: int}
     */
    public function findForUser(User $user, ?SharedImageStatus $status, int $page, int $limit): array
    {
        $qb = $this->createQueryBuilder('s')
            ->where('s.recipientUser = :user')
            ->setParameter('user', $user)
            ->orderBy('s.sharedAt', 'DESC');

        if ($status !== null) {
            $qb->andWhere('s.status = :status')->setParameter('status', $status);
        }

        $total = (clone $qb)->select('COUNT(s.id)')->resetDQLPart('orderBy')->getQuery()->getSingleScalarResult();

        $items = $qb
            ->setFirstResult(($page - 1) * $limit)
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();

        return ['items' => $items, 'total' => (int) $total];
    }

    public function pendingCountForUser(User $user): int
    {
        return (int) $this->createQueryBuilder('s')
            ->select('COUNT(s.id)')
            ->where('s.recipientUser = :user')
            ->andWhere('s.status = :status')
            ->setParameter('user', $user)
            ->setParameter('status', SharedImageStatus::Pending)
            ->getQuery()
            ->getSingleScalarResult();
    }
}
