<?php

namespace DMD\LaLigaApi\Service\Season\addTeam;

use DMD\LaLigaApi\Dto\TeamDto;
use DMD\LaLigaApi\Exception\ValidationException;
use DMD\LaLigaApi\Repository\SeasonRepository;
use DMD\LaLigaApi\Service\Common\AuthorizeRequest;
use DMD\LaLigaApi\Service\Common\TeamFactory;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;

class HandleAddTeamList
{
    public function __construct(
        public AuthorizeRequest $authorizeRequest,
        public TeamFactory $teamFactory,
        public EntityManagerInterface $entityManager,
        public SeasonRepository $seasonRepository
    ){}

    /**
     * @throws ValidationException
     */
    public function __invoke(
        Request $request,
        int $leagueId,
        int $seasonId
    ): JsonResponse
    {
        $this->authorizeRequest->authorizeLeaguePresident($leagueId);
        $seasonEntity = $this->seasonRepository->find($seasonId);
        if (is_null($seasonEntity))
        {
            throw new HttpException(
                Response::HTTP_NOT_FOUND,
                'Temporada con ID: '. $seasonId .' no ha sido encontrada.'
            );
        }
        if (empty($request->toArray()))
        {
            throw new HttpException(Response::HTTP_BAD_REQUEST, 'Empty request.');
        }
        $teamDtoList = [];
        foreach ($request->toArray() as $teamItem)
        {
            $teamDto = $this->teamFactory::createDtoFromArray($teamItem);
            $teamDto->validate();
            $teamEntity = $this->teamFactory::createEntityFromDto($teamDto);
            $teamEntity->addSeason($seasonEntity);
            $teamEntity->setLeagueId($leagueId);
            $this->entityManager->persist($teamEntity);
            $this->entityManager->flush();
            $teamDto->id = $teamEntity->getId();
            $teamDtoList[] = $teamDto->toArray();
        }
        return new JsonResponse(
            data: [
                'success' => true,
                'team' => $teamDtoList
            ],
            status: Response::HTTP_OK
        );
    }
}