<?php

namespace DMD\LaLigaApi\Service\League\acceptJoinLeagueRequest;

use DMD\LaLigaApi\Entity\CustomRole;
use DMD\LaLigaApi\Entity\League;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Enum\Role;
use DMD\LaLigaApi\Repository\LeagueRepository;
use DMD\LaLigaApi\Repository\TeamRepository;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\Common\AuthorizeRequest;
use DMD\LaLigaApi\Service\Common\EmailSender;
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 HandleAcceptJoinLeagueRequest
{
    public function __construct(
        public EntityManagerInterface $entityManager,
        public Security $security,
        public AuthorizeRequest $authorizeRequest,
        public UserRepository $userRepository,
        public LeagueRepository $leagueRepository,
        public TeamRepository $teamRepository,
        public EmailSender $emailSender
    ){}

    /**
     * @throws TransportExceptionInterface
     */
    public function __invoke(Request $request, int $leagueId, int $userId): JsonResponse
    {
        $leagueAdminEntity = $this->security->getUser();
        if (!$leagueAdminEntity instanceof User)
        {
            throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'Internal Server Error');
        }
        $this->authorizeRequest->isLeaguePresident($leagueId, $leagueAdminEntity);
        $leagueEntity = $this->leagueRepository->find($leagueId);
        if (is_null($leagueEntity))
        {
            throw new HttpException(Response::HTTP_NOT_FOUND, "Liga con id $leagueId no ha sido encontrada");
        }
        $requestingUserEntity = $this->userRepository->find($userId);
        if (is_null($requestingUserEntity))
        {
            throw new HttpException(Response::HTTP_NOT_FOUND,"El usuario con id: $userId no ha sido encontrado.");
        }
        $customRoleEntity = new CustomRole();
        $customRoleEntity->setName(Role::LEAGUE_MEMBER->value);
        $customRoleEntity->setEntityId($leagueId);
        $customRoleEntity->setUser($requestingUserEntity);
        $this->entityManager->persist($customRoleEntity);
        $this->entityManager->flush();
        $this->emailSender->joinLeagueRequestAccepted(
            $requestingUserEntity,
            $leagueEntity
        );
        return new JsonResponse(
            data: [
                'success' => true,
            ],
            status: Response::HTTP_OK
        );
    }
}