<?php

declare(strict_types=1);

namespace OCA\RePod\Controller;

use OCA\RePod\AppInfo\Application;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\JSONResponse;
use OCP\Http\Client\IClientService;
use OCP\IRequest;
use OCP\IUserSession;
use OCP\L10N\IFactory;

class SearchController extends Controller
{
	public function __construct(
		IRequest $request,
		private IClientService $clientService,
		private IFactory $l10n,
		private IUserSession $userSession
	) {
		parent::__construct(Application::APP_ID, $request);
	}

	public function index(string $value): JSONResponse
	{
		$podcasts = [];

		try {
			$fyydClient = $this->clientService->newClient();
			$fyydReponse = $fyydClient->get('https://api.fyyd.de/0.2/search/podcast', [
				'query' => [
					'title' => $value,
					'term' => $value,
				],
			]);
			$fyydJson = (array) json_decode((string) $fyydReponse->getBody(), true, flags: JSON_THROW_ON_ERROR);

			if (array_key_exists('data', $fyydJson) && is_array($fyydJson['data'])) {
				/** @var string[] $fyydFeed */
				foreach ($fyydJson['data'] as $fyydFeed) {
					$lastPub = date_format(new \DateTime($fyydFeed['lastpub']), DATE_ATOM);

					if ($lastPub) {
						$podcasts[] = [
							'provider' => 'fyyd',
							'id' => $fyydFeed['id'],
							'title' => $fyydFeed['title'],
							'author' => $fyydFeed['author'],
							'image' => $fyydFeed['imgURL'],
							'provider_url' => $fyydFeed['htmlURL'],
							'feed_url' => $fyydFeed['xmlURL'],
							'last_pub' => $lastPub,
							'nb_episodes' => $fyydFeed['episode_count'],
						];
					}
				}
			}
		} catch (\Exception $e) {
		}

		try {
			$itunesClient = $this->clientService->newClient();
			$itunesResponse = $itunesClient->get('https://itunes.apple.com/search', [
				'query' => [
					'media' => 'podcast',
					'term' => $value,
					'lang' => $this->l10n->getUserLanguage($this->userSession->getUser()),
				],
			]);
			$itunesJson = (array) json_decode((string) $itunesResponse->getBody(), true, flags: JSON_THROW_ON_ERROR);

			if (array_key_exists('data', $itunesJson) && is_array($itunesJson['data'])) {
				/** @var string[] $itunesFeed */
				foreach ($itunesJson['results'] as $itunesFeed) {
					$lastPub = date_format(new \DateTime($itunesFeed['releaseDate']), DATE_ATOM);

					if ($lastPub) {
						$podcasts[] = [
							'id' => $itunesFeed['id'],
							'title' => $itunesFeed['trackName'],
							'author' => $itunesFeed['artistName'],
							'image' => $itunesFeed['artworkUrl600'],
							'provider_url' => $itunesFeed['trackViewUrl'],
							'feed_url' => $itunesFeed['feedUrl'],
							'last_pub' => $lastPub,
							'nb_episodes' => $itunesFeed['trackCount'],
						];
					}
				}
			}
		} catch (\Exception $e) {
		}

		usort($podcasts, fn (array $a, array $b) => new \DateTime((string) $b['last_pub']) <=> new \DateTime((string) $a['last_pub']));
		$podcasts = array_intersect_key($podcasts, array_unique(array_map(fn (array $feed) => $feed['feed_url'], $podcasts)));

		return new JSONResponse($podcasts);
	}
}