<?php

namespace DMD\LaLigaApi\Service\User\Handlers\getNotifications;

use DMD\LaLigaApi\Dto\NotificationDto;
use DMD\LaLigaApi\Dto\UserDto;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Repository\NotificationRepository;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\User\Handlers\UserSaver;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class HandleGetNotifications
{
        public function __construct(
            public EntityManagerInterface $entityManager,
            public NotificationRepository $notificationRepository,
            public Security $security
        ){}

        public function __invoke(): JsonResponse
        {
            $user = $this->security->getUser();
            $notifications = $this->notificationRepository->findBy(
                criteria: [
                'userToNotify' => $user
                ],
                orderBy: [
                    'createdAt' => 'DESC'
                ]
            );
            if (empty($notifications))
            {
                return new JsonResponse([
                    'success' => true,
                    'notifications' => []
                ], Response::HTTP_OK);
            }
            $notificationDtoList = [];
            foreach ($notifications as $notificationObj)
            {
                if (
                    ($notificationObj->isIsRead()) &&
                    (($notificationObj->getReadAt())->diff(new \DateTime('now'))->days > 30)
                )
                {
                    $this->entityManager->remove($notificationObj);
                    continue;
                }
                if (!$notificationObj->isIsRead())
                {
                    $notificationObj->setIsRead(true);
                    $notificationObj->setReadAt(new \DateTimeImmutable('now'));
                    $this->entityManager->persist($notificationObj);
                }
                $notificationDto = new NotificationDto();
                $notificationDtoList[] = ($notificationDto->fillFromObj($notificationObj))->toArray();
            }
            $this->entityManager->flush();
            return new JsonResponse(
                data: [
                    'success' => true,
                    'notifications' => $notificationDtoList
                ],
                status: Response::HTTP_OK
            );
        }
}