<?php

namespace DMD\LaLigaApi\Service\Season\updateSeason;

use DMD\LaLigaApi\Dto\SeasonDto;
use DMD\LaLigaApi\Entity\Season;
use DMD\LaLigaApi\Repository\CustomRoleRepository;
use DMD\LaLigaApi\Repository\SeasonRepository;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\Season\SeasonFactory;
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 HandleUpdateSeason
{
    public function __construct(
        public SeasonFactory          $seasonSaver,
        public EntityManagerInterface $entityManager,
        public Security               $security,
        public SeasonRepository       $seasonRepository,
        public CustomRoleRepository   $customRoleRepository,
        public UserRepository         $userRepository
    ){}

    public function __invoke(Request $request, int $leagueId, int $seasonId): JsonResponse
    {
        $seasonObj = $this->checkUserAuthorization($leagueId, $seasonId);
        $seasonDto = new SeasonDto();
        $seasonDto->fillFromEntity($seasonObj);
        $seasonDto->fillFromArray($request->toArray());
        $seasonDto->validate();
        if (!empty($seasonDto->validationErrors))
        {
            return $this->generateErrorResponse($seasonDto->validationErrors);
        }
        $seasonObj->setActive(true);
        $this->seasonSaver->save($seasonObj, $seasonDto);
        $this->entityManager->flush();
        return new JsonResponse(
            data: [
                'success' => true,
                'season' => $seasonDto->createSeasonArray()
            ],
            status: Response::HTTP_OK
        );
    }

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

    public function checkUserAuthorization(int $leagueId, int $seasonId): Season
    {
        $user = $this->security->getUser();
        if (is_null($user))
        {
            throw new HttpException(Response::HTTP_FORBIDDEN, "Usuario no encontrado.");
        }
        $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.");
        }
        $seasonObj = $this->seasonRepository->find($seasonId);
        if (is_null($seasonObj))
        {
            throw new HttpException(Response::HTTP_NOT_FOUND, 'Temporada no encontrada.');
        }
        return $seasonObj;
    }
}