<?php

namespace DMD\LaLigaApi\Service\League\newJoinLeagueRequest;

use DMD\LaLigaApi\Dto\NotificationDto;
use DMD\LaLigaApi\Entity\League;
use DMD\LaLigaApi\Entity\Notification;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Repository\CustomRoleRepository;
use DMD\LaLigaApi\Repository\LeagueRepository;
use DMD\LaLigaApi\Repository\TeamRepository;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\Common\NotificationFactory;
use DMD\LaLigaApi\Service\League\LeagueFactory;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
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\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;

class HandleNewJoinLeagueRequest
{
    public function __construct(
        public Security $security,
        public LeagueRepository $leagueRepository,
        public NotificationFactory $notificationFactory,
        public MailerInterface $mailer
    ){}

    /**
     * @throws TransportExceptionInterface
     */
    public function __invoke(
        Request $request,
        int $leagueId
    ): JsonResponse
    {
        $requestingUser = $this->security->getUser();
        if (!($requestingUser instanceof User))
        {
            throw new HttpException(
                Response::HTTP_FORBIDDEN,
                "Unauthorized.");
        }
        $leagueToJoin = $this->leagueRepository->find($leagueId);
        if (is_null($leagueToJoin))
        {
            throw new HttpException(
                Response::HTTP_NOT_FOUND,
                'Liga no encontrada.');
        }

        $this->notificationFactory->newJoinLeagueRequest(
            $requestingUser,
            $leagueToJoin,
            ($request->toArray())['message'] ?? null
        );
        return new JsonResponse(
            data: [
                'success' => true,
                'message' => 'La solicitud ha sido enviada correctamente.'
            ],
            status: Response::HTTP_OK
        );
    }
}