<?php

namespace DMD\LaLigaApi\Service\Season\getAllFacilities;

use DMD\LaLigaApi\Dto\FacilityDto;
use DMD\LaLigaApi\Dto\SeasonDto;
use DMD\LaLigaApi\Entity\Season;
use DMD\LaLigaApi\Repository\FacilityRepository;
use DMD\LaLigaApi\Repository\SeasonRepository;
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 HandleGetAllFacilities
{
    public const PAGE_SIZE = 10;

    public function __construct(
        public EntityManagerInterface $entityManager,
        public FacilityRepository $facilityRepository,
        public SeasonRepository $seasonRepository
    ){}

    public function __invoke(Request $request, int $leagueId, int $seasonId): JsonResponse
    {
        $seasonEntity = $this->seasonRepository->find($seasonId);
        if (!$seasonEntity instanceof Season)
        {
            throw new HttpException(Response::HTTP_NOT_FOUND, 'Season not found, check id');
        }
        $facilityCollection = $this->facilityRepository->findBy([
            'season' => $seasonEntity,
            'active' => true
        ]);
        $facilityArray = [];
        if (!is_null($facilityCollection))
        {
            foreach ($facilityCollection as $facilityObj)
            {
                $facilityDto = new FacilityDto();
                $facilityDto->fillFromObject($facilityObj);
                $facilityArray[] = $facilityDto->toArray();
            }
        }
        return new JsonResponse(
            data: [
                'success' => true,
                'facilities' => $facilityArray
            ],
            status: Response::HTTP_OK
        );
    }
}