<?php

declare(strict_types=1);

namespace OCA\RePod\Service;

use OCP\Http\Client\IClientService;

class ItunesService implements IProvider
{
	private const BASE_URL = 'https://itunes.apple.com/';

	public function __construct(
		private IClientService $clientService,
		private UserService $userService
	) {
	}

	public function search(string $value): array
	{
		$podcasts = [];

		$client = $this->clientService->newClient();
		$response = $client->get(self::BASE_URL.'search', [
			'query' => [
				'media' => 'podcast',
				'term' => $value,
				'country' => $this->userService->getCountryCode(),
			],
		]);
		$json = (array) json_decode((string) $response->getBody(), true, flags: JSON_THROW_ON_ERROR);

		if (array_key_exists('data', $json) && is_array($json['data'])) {
			/** @var string[] $feed */
			foreach ($json['results'] as $feed) {
				$podcasts[] = [
					'provider' => 'itunes',
					'id' => $feed['id'],
					'title' => $feed['trackName'],
					'author' => $feed['artistName'],
					'image' => $feed['artworkUrl600'],
					'provider_url' => $feed['trackViewUrl'],
					'feed_url' => $feed['feedUrl'],
					'last_pub' => $feed['releaseDate'],
					'nb_episodes' => $feed['trackCount'],
				];
			}
		}

		return $podcasts;
	}
}