<?php

namespace DMD\LaLigaApi\Service\League\updateLeague;

use DMD\LaLigaApi\Dto\LeagueDto;
use DMD\LaLigaApi\Entity\League;
use DMD\LaLigaApi\Repository\CustomRoleRepository;
use DMD\LaLigaApi\Repository\LeagueRepository;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\League\LeagueFactory;
use Doctrine\ORM\EntityManagerInterface;
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;

class HandleUpdateLeague
{
    public function __construct(
        public LeagueFactory          $leagueSaver,
        public EntityManagerInterface $entityManager,
        public Security               $security,
        public UserRepository         $userRepository,
        public LeagueRepository       $leagueRepository,
        public CustomRoleRepository   $customRoleRepository,
    ){}

    public function __invoke(Request $request, int $leagueId): JsonResponse
    {
        $authorizationResult = $this->checkUserAuthorization($leagueId);
        $leagueDto = new LeagueDto();
        $leagueDto->fillFromObject($authorizationResult['leagueObj']);
        $leagueDto->fillFromArray($request->toArray());
        $leagueDto->validate();
        if (!empty($leagueDto->validationErrors))
        {
            return $this->generateErrorResponse($leagueDto->validationErrors);
        }
        $this->leagueSaver->save($authorizationResult['leagueObj'], $leagueDto);
        $this->entityManager->flush();
        return new JsonResponse(
            data: [
                'success' => true,
                'league' => $leagueDto->toArray()
            ],
            status: Response::HTTP_OK
        );
    }

    public function generateErrorResponse(array $validationErrors): JsonResponse
    {
        return new JsonResponse(
            data: [
                'success' => false,
                'error' => $validationErrors
            ],
            status: Response::HTTP_OK
        );
    }

    public function checkUserAuthorization(int $leagueId): array
    {
        $user = $this->security->getUser();
        if (is_null($user))
        {
            throw new HttpException(Response::HTTP_FORBIDDEN, "Unauthorized.");
        }
        $customRole = $this->customRoleRepository->findBy([
            'name' => $leagueId.'_LEAGUE_PRESIDENT',
            'user' => $user
        ]);
        if (is_null($customRole))
        {
            throw new HttpException(Response::HTTP_FORBIDDEN, "Usuario no tiene permiso para editar la liga.");
        }
        $leagueObj = $this->leagueRepository->find($leagueId);
        if (is_null($leagueObj))
        {
            throw new HttpException(Response::HTTP_NOT_FOUND, "Liga con id: ". $leagueId .' no ha sido encontrada.');
        }
        return [
            'leagueObj' => $leagueObj,
            'userObj' => $user
        ];
    }
}