<?php

declare(strict_types=1);

namespace OCA\RePod\Controller;

use OCA\GPodderSync\Db\EpisodeAction\EpisodeActionRepository;
use OCA\RePod\AppInfo\Application;
use OCA\RePod\Core\EpisodeAction\EpisodeActionExtraData;
use OCA\RePod\Core\EpisodeAction\EpisodeActionReader;
use OCA\RePod\Service\UserService;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\FrontpageRoute;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
use OCP\AppFramework\Http\JSONResponse;
use OCP\Http\Client\IClientService;
use OCP\IRequest;

class EpisodesController extends Controller
{
	public function __construct(
		IRequest $request,
		private readonly EpisodeActionReader $episodeActionReader,
		private readonly EpisodeActionRepository $episodeActionRepository,
		private readonly IClientService $clientService,
		private readonly UserService $userService
	) {
		parent::__construct(Application::APP_ID, $request);
	}

	#[NoAdminRequired]
	#[NoCSRFRequired]
	#[FrontpageRoute(verb: 'GET', url: '/episodes/list')]
	public function list(string $url): JSONResponse {
		$client = $this->clientService->newClient();
		$feed = $client->get($url);
		$episodes = $this->episodeActionReader->parseRssXml((string) $feed->getBody());
		usort($episodes, fn (EpisodeActionExtraData $a, EpisodeActionExtraData $b): int => $b->getPubDate() <=> $a->getPubDate());
		$episodes = array_values(array_intersect_key($episodes, array_unique(array_map(fn (EpisodeActionExtraData $episode): string => $episode->getGuid(), $episodes))));

		/** @var Http::STATUS_* $returnStatusCode */
		$returnStatusCode = $feed->getStatusCode();

		return new JSONResponse($episodes, $returnStatusCode);
	}

	#[NoAdminRequired]
	#[NoCSRFRequired]
	#[FrontpageRoute(verb: 'GET', url: '/episodes/action')]
	public function action(string $url): JSONResponse {
		$action = $this->episodeActionRepository->findByEpisodeUrl($url, $this->userService->getUserUID());

		if ($action) {
			return new JSONResponse($action->toArray());
		}

		return new JSONResponse([], Http::STATUS_NOT_FOUND);
	}
}
