<?php

namespace BitApps\PiPro\src\Integrations\Emailit;

use BitApps\Pi\Helpers\MixInputHandler;
use BitApps\Pi\Helpers\Utility;
use BitApps\Pi\src\Authorization\AuthorizationFactory;
use BitApps\Pi\src\Authorization\AuthorizationType;
use BitApps\Pi\src\Flow\NodeInfoProvider;
use BitApps\Pi\src\Interfaces\ActionInterface;
use BitApps\PiPro\Deps\BitApps\WPKit\Http\Client\HttpClient;

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

class EmailitAction implements ActionInterface
{
    private NodeInfoProvider $nodeInfoProvider;

    private EmailitService $emailitService;

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

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

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

    private function executeMachine($machineSlug, $fieldMapData, $configs)
    {
        switch ($machineSlug) {
            case 'createAudience':
                return $this->emailitService->createAudience($fieldMapData);

            case 'subscribeToAudience':
                $mixInputTokenId = $this->nodeInfoProvider->getFieldMapConfigs('token-id.value');
                $tokenId = MixInputHandler::replaceMixTagValue($mixInputTokenId);

                return $this->emailitService->subscribeToAudience($tokenId, $fieldMapData);

            case 'sendEmail':
                return $this->emailitService->sendEmail($configs['mail-format'], $fieldMapData);
        }
    }

    private function executeEmailitAction()
    {
        $machineSlug = $this->nodeInfoProvider->getMachineSlug();
        $configs = $this->nodeInfoProvider->getFieldMapConfigs();
        $fieldMapData = $this->nodeInfoProvider->getFieldMapData();

        $accessToken = AuthorizationFactory::getAuthorizationHandler(
            AuthorizationType::BEARER_TOKEN,
            $configs['connection-id']
        )->getAccessToken();

        $httpClient = new HttpClient(
            [
                'headers' => [
                    'Content-Type'  => 'application/json',
                    'Authorization' => $accessToken
                ],
            ]
        );

        $this->emailitService = new EmailitService($httpClient);

        return $this->executeMachine($machineSlug, $fieldMapData, $configs);
    }
}
