<?php

use YesWiki\Bazar\Service\FormManager;
use YesWiki\Core\YesWikiAction;
use YesWiki\Bazar\Service\ActivityPubService;
use YesWiki\Bazar\Service\WebfingerService;

class BazarFollowAction extends YesWikiAction
{
    public function run()
    {
        $activityPubService = $this->getService(ActivityPubService::class);
        $webfingerService = $this->getService(WebfingerService::class);

        $formId = $this->arguments['id'];
        $form = $this->getService(FormManager::class)->getOne($formId);

        if (isset($_POST['actor_handle']) && $_POST['form_id'] == $formId) {
            $formActorUri = $activityPubService->getFormActorUri($form);

            $interactionUrl = $webfingerService->getInteractionUrl($_POST['actor_handle'], $formActorUri);

            return $this->wiki->redirect($interactionUrl);
        }

        $activityPubEnabled = $activityPubService->isEnabled($form);

        if ($activityPubEnabled) {
            return $this->render('@bazar/follow.twig', [
                'form' => $form,
            ]);
        }
    }
}
