<?php

namespace PublishPress\FuturePro\Modules\Workflows\Domain\Steps\Actions\Runners;

use PublishPress\Future\Core\HookableInterface;
use PublishPress\Future\Framework\Logger\LoggerInterface;
use PublishPress\Future\Modules\Workflows\Domain\Engine\VariableResolvers\IntegerResolver;
use PublishPress\Future\Modules\Workflows\Domain\Steps\Actions\Definitions\AddPostMeta;
use PublishPress\Future\Modules\Workflows\Interfaces\ExecutionContextInterface;
use PublishPress\Future\Modules\Workflows\Interfaces\StepProcessorInterface;
use PublishPress\Future\Modules\Workflows\Interfaces\StepRunnerInterface;

class AddPostMetaRunner implements StepRunnerInterface
{
    /**
     * @var HookableInterface
     */
    private $hooks;

    /**
     * @var StepProcessorInterface
     */
    private $stepProcessor;

    /**
     * @var \Closure
     */
    private $expirablePostModelFactory;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var ExecutionContextInterface
     */
    private $executionContext;

    public function __construct(
        HookableInterface $hooks,
        StepProcessorInterface $stepProcessor,
        \Closure $expirablePostModelFactory,
        ExecutionContextInterface $executionContext,
        LoggerInterface $logger
    ) {
        $this->hooks = $hooks;
        $this->stepProcessor = $stepProcessor;
        $this->expirablePostModelFactory = $expirablePostModelFactory;
        $this->executionContext = $executionContext;
        $this->logger = $logger;
    }

    public static function getNodeTypeName(): string
    {
        return AddPostMeta::getNodeTypeName();
    }

    public function setup(array $step): void
    {
        $this->stepProcessor->setup($step, [$this, 'actionCallback']);
    }

    public function actionCallback(int $postId, array $nodeSettings, array $step)
    {
        $this->stepProcessor->executeSafelyWithErrorHandling(
            $step,
            function ($step, $postId, $nodeSettings) {
                $nodeSlug = $this->stepProcessor->getSlugFromStep($step);

                $postModel = call_user_func($this->expirablePostModelFactory, $postId);

                $metaValue = $this->executionContext->resolveExpressionsInText(
                    $nodeSettings['metaValue']['expression']
                );
                $isSingle = $nodeSettings['isSingle'] ?? true;

                $metaId = $postModel->addMeta($nodeSettings['metaKey'], $metaValue, $isSingle);

                if (empty($metaId)) {
                    $this->logger->debug(
                        $this->stepProcessor->prepareLogMessage(
                            'Post meta not added | Post ID: %1$s | Slug: %2$s | Meta Key: %3$s | Meta Value: %4$s',
                            $postId,
                            $nodeSlug,
                            $nodeSettings['metaKey'],
                            $metaValue
                        )
                    );

                    return;
                } else {
                    $this->executionContext->setVariable($nodeSlug, [
                        'metaId' => new IntegerResolver($metaId),
                    ]);

                    $this->logger->debug(
                        $this->stepProcessor->prepareLogMessage(
                            'Post meta added | Post ID: %1$s | Slug: %2$s | Meta Key: %3$s | Meta Value: %4$s',
                            $postId,
                            $nodeSlug,
                            $nodeSettings['metaKey'],
                            $metaValue
                        )
                    );
                }
            },
            $postId,
            $nodeSettings
        );
    }
}
