<?php

namespace App\Controller;

use App\Service\SpotifyApiService;
use App\Service\SpotifyPlaylistService;
use SpotifyWebAPI\SpotifyWebAPI;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;

class ArtistController extends AbstractController
{
    private SpotifyWebAPI $spotifyApi;

    public function __construct(SpotifyApiService $spotifyApiService)
    {
        // increase timeout limit
        set_time_limit(60);

        $this->spotifyApi = $spotifyApiService->createApi();
    }

    /**
     * @Route("/artists/top", name="get-artists-top")
     */
    public function getArtists(): JsonResponse
    {
        $rawTopArtists = $this->spotifyApi->getMyTop(
            'artists',
            [
                'limit' => SpotifyPlaylistService::TOP_ARTISTS_COUNT,
                'time_range' => 'short_term'
            ]
        )->items;

        $artists = [];
        foreach ($rawTopArtists as $artist) {
            $artists[] = [
                'id' => $artist->id,
                'name' => $artist->name,
                'imageUrl' => $artist->images[\count($artist->images) - 1]->url,
            ];
        }

        return new JsonResponse($artists);
    }
}