<?php

namespace DMD\LaLigaApi\Service\League\getLeagueById;

use DMD\LaLigaApi\Dto\LeagueDto;
use DMD\LaLigaApi\Repository\LeagueRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;

class HandleGetLeagueById
{
    public function __construct(
        public LeagueRepository $leagueRepository,
    ){}

    public function __invoke(Request $request, int $leagueId): JsonResponse
    {
        $leagueEntity = $this->leagueRepository->find($leagueId);
        if (is_null($leagueEntity))
        {
            throw new HttpException(
                Response::HTTP_NOT_FOUND,
                "Liga no encontrada"
            );
        }
        $leagueDto = new LeagueDto();
        $leagueDto->fillFromObject($leagueEntity);
        return new JsonResponse(
            data: [
                'success' => true,
                'league' => $leagueDto->toArray()
            ],
            status: Response::HTTP_OK
        );
    }
}