<?php

namespace App\Rating\Repository;

use App\Auth\Entity\User;
use App\Rating\Entity\Comment;
use App\Rating\Entity\Like;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class LikeRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry) { parent::__construct($registry, Like::class); }

    public function findByUserAndComment(User $user, Comment $comment): ?Like { return $this->findOneBy(['user' => $user, 'comment' => $comment]); }

    /** @return array{like_count:int,dislike_count:int} */
    public function countByComment(Comment $comment): array
    {
        $rows = $this->createQueryBuilder('l')
            ->select('l.value as value, COUNT(l.id) as cnt')
            ->where('l.comment = :comment')
            ->setParameter('comment', $comment)
            ->groupBy('l.value')
            ->getQuery()->getResult();

        $likeCount = 0;
        $dislikeCount = 0;
        foreach ($rows as $row) {
            if ((int) $row['value'] >= 0) {
                $likeCount = (int) $row['cnt'];
            } else {
                $dislikeCount = (int) $row['cnt'];
            }
        }

        return ['like_count' => $likeCount, 'dislike_count' => $dislikeCount];
    }

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