<?php

namespace DMD\LaLigaApi\Service\Season\getAllTeams;

use DMD\LaLigaApi\Repository\LeagueRepository;
use DMD\LaLigaApi\Repository\SeasonRepository;
use DMD\LaLigaApi\Repository\TeamRepository;
use DMD\LaLigaApi\Service\Common\TeamFactory;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;

class HandleGetAllTeams
{
    public function __construct(
        public TeamRepository $teamRepository,
        public SeasonRepository $seasonRepository,
        public LeagueRepository $leagueRepository,
        public TeamFactory $teamFactory,
    )
    {
    }

    public function __invoke(Request $request ,int $leagueId, int $seasonId): JsonResponse
    {
        $leagueEntity = $this->leagueRepository->find($leagueId);
        $seasonEntity = $this->seasonRepository->findOneBy([
            'id' => $seasonId,
            'league' => $leagueEntity
        ]);
        if (is_null($seasonEntity))
        {
            throw new HttpException(Response::HTTP_NOT_FOUND, "Season not found");
        }
        $teamEntityCollection = $this->teamRepository->findBy([
            'leagueId' => $leagueId,
            'active' => true
        ]);
        if (empty($teamEntityCollection))
        {
            return new JsonResponse([
                'success' => true,
                'teams' => []
            ], Response::HTTP_OK);
        }
        $teamArray = [];
        foreach ($teamEntityCollection as $teamEntity)
        {
            $teamArray[] = ($this->teamFactory::createDtoFromEntity($teamEntity))->toArray();
        }
        return new JsonResponse(
            [
                'success' => true,
                'teams' => $teamArray
            ], Response::HTTP_OK
        );
    }
}