<?php

namespace DMD\LaLigaApi\Service\Season\createFacilities;

use DMD\LaLigaApi\Dto\FacilityDto;
use DMD\LaLigaApi\Entity\Season;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Exception\ValidationException;
use DMD\LaLigaApi\Repository\SeasonRepository;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\Common\AuthorizeRequest;
use DMD\LaLigaApi\Service\Common\FacilityFactory;
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 HandleCreateFacilities
{
    public function __construct(
        public AuthorizeRequest          $authorizeRequest,
        public FacilityFactory          $facilityFactory,
        public EntityManagerInterface $entityManager,
        public Security               $security,
        public UserRepository         $userRepository,
        public SeasonRepository         $seasonRepository
    ){}

    /**
     * @throws ValidationException
     */
    public function __invoke(Request $request, int $leagueId, int $seasonId): JsonResponse
    {
        $userEntity = $this->security->getUser();
        $this->authorizeRequest->authorizeLeaguePresident($leagueId);
        if ((!$userEntity instanceof User))
        {
            throw new HttpException(Response::HTTP_FORBIDDEN, "Unauthorized.");
        }
        $seasonEntity = $this->seasonRepository->find($seasonId);
        if (!$seasonEntity instanceof Season)
        {
            throw new HttpException(Response::HTTP_NOT_FOUND, 'Season not found, check id.');
        }
        $facilityEntityList = [];
        foreach ($request->toArray() as $facilityItem)
        {
            $facilityDto = new FacilityDto();
            $facilityDto->fillFromArray($facilityItem);
            $facilityDto->validate();
            $facilityEntity = $this->facilityFactory::create($facilityDto);
            $facilityEntity->setSeason($seasonEntity);
            $this->entityManager->persist($facilityEntity);
            $facilityEntityList[] = $facilityEntity;
        }
        $this->entityManager->flush();
        $facilityResponseArray = [];
        foreach ($facilityEntityList as $facilityEntity)
        {
            $facilityDto = new FacilityDto();
            $facilityDto->fillFromObject($facilityEntity);
            $facilityResponseArray[] = $facilityDto->toArray();
        }
        return new JsonResponse(
            data: [
                'success' => true,
                'facilities' => $facilityResponseArray
            ],
            status: Response::HTTP_OK
        );
    }
}