<?php

namespace BitApps\PiPro\src\Integrations\Poptics;

use BitApps\Pi\Helpers\Utility;
use BitApps\Pi\src\Flow\NodeInfoProvider;
use BitApps\Pi\src\Interfaces\ActionInterface;

if (!\defined('ABSPATH')) {
    exit;
}

class PopticsAction implements ActionInterface
{
    private $nodeInfoProvider;

    public function __construct(NodeInfoProvider $nodeInfoProvider)
    {
        $this->nodeInfoProvider = $nodeInfoProvider;
    }

    public function execute(): array
    {
        $executedNodeAction = $this->executePopticsAction();

        return Utility::formatResponseData(
            $executedNodeAction['status_code'] ?? 200,
            $executedNodeAction['payload'] ?? [],
            $executedNodeAction['response'] ?? []
        );
    }

    private function executePopticsAction()
    {
        if (!class_exists('Poptics')) {
            return [
                'status_code' => 400,
                'payload'     => [],
                'response'    => __('Poptics plugin is not active.', 'bit-pi'),
            ];
        }

        $popticsService = new PopticsService($this->nodeInfoProvider);

        $machineSlug = $this->nodeInfoProvider->getMachineSlug();

        if (!method_exists($popticsService, $machineSlug)) {
            return [
                'status_code' => 400,
                'payload'     => [],
                'response'    => __('Poptics action not found.', 'bit-pi'),
            ];
        }

        return $popticsService->{$machineSlug}();
    }
}
