<?php

namespace BitApps\PiPro\src\Integrations\MailerPress;

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

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

class MailerPressAction implements ActionInterface
{
    private $nodeInfoProvider;

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

    public function execute(): array
    {
        if (!class_exists('\MailerPress\Core\Kernel')) {
            return Utility::formatResponseData(500, [], __('MailerPress is not installed or activated', 'bit-pi'));
        }

        $executedNodeAction = $this->executeMailerPressAction();

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

    private function executeMailerPressAction()
    {
        $mailerPressService = new MailerPressServices($this->nodeInfoProvider);

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

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

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