<?php

namespace DMD\LaLigaApi\Service\League\declineJoinLeagueRequest;

use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Repository\LeagueRepository;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\Common\AuthorizeRequest;
use DMD\LaLigaApi\Service\Common\NotificationFactory;
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;

class HandleDeclineJoinLeagueRequest
{
    public function __construct(
        public Security $security,
        public UserRepository $userRepository,
        public LeagueRepository $leagueRepository,
        public AuthorizeRequest $authorizeRequest,
        public NotificationFactory $notificationFactory
    ){}

    /**
     * @throws TransportExceptionInterface
     */
    public function __invoke(
        Request $request,
        int $leagueId,
        int $rejectedUserId
    ): JsonResponse
    {
        $leagueAdmin = $request->getUser();
        if (!$leagueAdmin instanceof User)
        {
            throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'Internal Server Error');
        }

        $this->authorizeRequest->isLeaguePresident($leagueId, $leagueAdmin);
        $leagueEntity = $this->leagueRepository->find($leagueId);
        if (is_null($leagueEntity))
        {
            throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, "Liga con id: $leagueId no ha sido encontrada");
        }

        $rejectedUser = $this->userRepository->find($rejectedUserId);
        if (is_null($rejectedUser))
        {
            throw new HttpException(Response::HTTP_NOT_FOUND, "El usuario con id $rejectedUserId no ha sido encontrado.");
        }
        $this->notificationFactory->joinLeagueRequestDeclined($rejectedUser, $leagueEntity);
        return new JsonResponse(
            data: [
                'success' => true,
            ],
            status: Response::HTTP_OK
        );
    }
}