<?php

namespace Rdgcorp\MasterFeed\Application;

use Rdgcorp\MasterFeed\Infrastructure\MasterFeedClient;

class GetDirectTeams
{
    private MasterFeedClient $masterFeedClient;

    public function __construct(MasterFeedClient $masterFeedClient)
    {
        $this->masterFeedClient = $masterFeedClient;
    }

    public function __invoke(?string $leagueId = null): array
    {
        $sportId = null;

        if ($leagueId) {
            $getDirectLeagues = new GetDirectLeagues($this->masterFeedClient);

            foreach ($getDirectLeagues as $league) {
                if ($league['id'] === $leagueId) {
                    $sportId = $league['sport_id'];
                }
            }
        }

        $responseData = $this->masterFeedClient->getDirectTeams($sportId);

        $data = $responseData[0]['data-content'][0][0]['teams'];

        if ($leagueId) {
            foreach ($data as $key => $item) {
                if ($item['league_id'] !== $leagueId) {
                    unset($data[$key]);
                }
            }
        }

        return $data;
    }
}
