<?php

declare(strict_types=1);

namespace OCA\RePod\Service;

use OCP\Http\Client\IClientService;
use OCP\IUserSession;
use OCP\L10N\IFactory;
use Psr\Log\LoggerInterface;

/**
 * @psalm-import-type Podcast from IProvider
 */
class FyydService implements IProvider
{
	private const BASE_URL = 'https://api.fyyd.de/0.2/';

	public function __construct(
		private UserService $userService,
		private IClientService $clientService,
		private IFactory $l10n,
		private IUserSession $userSession,
		private LoggerInterface $logger
	) {
	}

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

		$client = $this->clientService->newClient();
		$response = $client->get(self::BASE_URL.'search/podcast', [
			'query' => [
				'title' => $value,
				'url' => $value,
				'term' => $value,
			],
		]);
		$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['data'] as $feed) {
				$podcasts[] = [
					'id' => $feed['id'],
					'provider' => 'fyyd',
					'website' => $feed['htmlURL'],
					'description' => $feed['description'],
					'title' => $feed['title'],
					'author' => $feed['author'],
					'url' => $feed['xmlURL'],
					'position_last_week' => $feed['rank'],
					'mygpo_link' => $feed['url_fyyd'],
					'logo_url' => $feed['imgURL'],
					'lastpub' => $feed['lastpub'],
					'episode_count' => $feed['episode_count'],
				];
			}
		}

		return $podcasts;
	}

	/**
	 * @return Podcast[]
	 */
	public function hot(int $count = 10): array
	{
		$podcasts = [];
		$language = 'en';
		$userLang = $this->userService->getLangCode();

		try {
			$langClient = $this->clientService->newClient();
			$langResponse = $langClient->get(self::BASE_URL.'feature/podcast/hot/languages');
			$langJson = (array) json_decode((string) $langResponse->getBody(), true, flags: JSON_THROW_ON_ERROR);
			if (array_key_exists('data', $langJson) && is_array($langJson['data'])) {
				$language = in_array($userLang, $langJson['data']) ? $userLang : 'en';
			}
		} catch (\Exception $e) {
			$this->logger->error($e->getMessage(), $e->getTrace());
		}

		$podcastClient = $this->clientService->newClient();

		$podcastResponse = $podcastClient->get(self::BASE_URL.'feature/podcast/hot', [
			'query' => [
				'count' => $count,
				'language' => $language,
			],
		]);
		$postCastJson = (array) json_decode((string) $podcastResponse->getBody(), true, flags: JSON_THROW_ON_ERROR);

		if (array_key_exists('data', $postCastJson) && is_array($postCastJson['data'])) {
			/** @var string[] $feed */
			foreach ($postCastJson['data'] as $feed) {
				$podcasts[] = [
					'id' => $feed['id'],
					'provider' => 'fyyd',
					'website' => $feed['htmlURL'],
					'description' => $feed['description'],
					'title' => $feed['title'],
					'author' => $feed['author'],
					'url' => $feed['xmlURL'],
					'position_last_week' => $feed['rank'],
					'mygpo_link' => $feed['url_fyyd'],
					'logo_url' => $feed['imgURL'],
					'lastpub' => $feed['lastpub'],
					'episode_count' => $feed['episode_count'],
				];
			}
		}

		return $podcasts;
	}
}