<?php

namespace DMD\LaLigaApi\Service\League\createLeague;

use DMD\LaLigaApi\Dto\LeagueDto;
use DMD\LaLigaApi\Entity\CustomRole;
use DMD\LaLigaApi\Entity\League;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Enum\Role;
use DMD\LaLigaApi\Exception\ValidationException;
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 HandleCreateLeague
{
    public function __construct(
        public LeagueFactory          $leagueFactory,
        public EntityManagerInterface $entityManager,
        public Security               $security,
        public UserRepository         $userRepository
    ){}

    /**
     * @throws ValidationException
     */
    public function __invoke(Request $request): JsonResponse
    {
        $userEntity = $this->userRepository->findOneBy([
            'email' => $this->security->getUser()?->getUserIdentifier()
        ]);
        if (is_null($userEntity))
        {
            throw new HttpException(Response::HTTP_FORBIDDEN, "Unauthorized.");
        }

        $leagueDto = new LeagueDto();
        $leagueDto->fillFromArray($request->toArray());
        $leagueDto->validate();
        $leagueDto->active = true;
        $leagueEntity = $this->leagueFactory::create($leagueDto);

        $this->entityManager->persist($leagueEntity);
        $this->entityManager->flush();
        $this->assignPresidentRole($leagueEntity->getId(), $userEntity);

        $leagueDto->id = $leagueEntity->getId();
        $leagueDto->createdAt = $leagueEntity->getCreatedAt();
        return new JsonResponse(
            data: [
                'success' => true,
                'league' => $leagueDto->toArray()
            ],
            status: Response::HTTP_OK
        );
    }
    public function assignPresidentRole(int $leagueId, User $userEntity): void
    {
        $leaguePresidentRole = new CustomRole();
        $leaguePresidentRole->setName(Role::LEAGUE_PRESIDENT->value);
        $leaguePresidentRole->setEntityId($leagueId);
        $leaguePresidentRole->setUser($userEntity);
        $this->entityManager->persist($leaguePresidentRole);
        $this->entityManager->flush();
    }
}