<?php

declare(strict_types=1);

namespace OCA\RePod\Service;

use OCA\GPodderSync\Core\PodcastData\PodcastData;
use OCP\Http\Client\IClientService;
use Psr\Log\LoggerInterface;

class FyydService implements IPodProvider
{
	private const BASE_URL = 'https://api.fyyd.de/0.2/';

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

	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) {
				if ($feed['title']) {
					$podcasts[] = new PodcastData(
						$feed['title'],
						$feed['author'],
						$feed['xmlURL'],
						$feed['description'],
						$feed['imgURL'],
						strtotime($feed['lastpub'])
					);
				}
			}
		}

		return $podcasts;
	}

	/**
	 * @return PodcastData[]
	 */
	public function latest(): array {
		$podcasts = [];
		$podcastClient = $this->clientService->newClient();
		$podcastResponse = $podcastClient->get(self::BASE_URL.'podcast/latest');
		$podcastJson = (array) json_decode((string) $podcastResponse->getBody(), true, flags: JSON_THROW_ON_ERROR);

		if (array_key_exists('data', $podcastJson) && is_array($podcastJson['data'])) {
			/** @var string[] $feed */
			foreach ($podcastJson['data'] as $feed) {
				if ($feed['title']) {
					$podcasts[] = new PodcastData(
						$feed['title'],
						$feed['author'],
						$feed['xmlURL'],
						$feed['description'],
						$feed['imgURL'],
						strtotime($feed['lastpub'])
					);
				}
			}
		}

		return $podcasts;
	}

	/**
	 * @return PodcastData[]
	 */
	public function hot(): 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 $exception) {
			$this->logger->error($exception->getMessage(), $exception->getTrace());
		}

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

		$podcastResponse = $podcastClient->get(self::BASE_URL.'feature/podcast/hot', [
			'query' => [
				'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) {
				if ($feed['title']) {
					$podcasts[] = new PodcastData(
						$feed['title'],
						$feed['author'],
						$feed['xmlURL'],
						$feed['description'],
						$feed['imgURL'],
						strtotime($feed['lastpub'])
					);
				}
			}
		}

		return $podcasts;
	}
}