<?php

namespace BitApps\PiPro\src\Integrations\GoogleMeet;

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;

if (!\defined('ABSPATH')) {
    exit;
}
class GoogleMeetAction implements ActionInterface
{
    private NodeInfoProvider $nodeInfoProvider;

    private GoogleMeetService $googleMeetService;

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

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

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

    private function executeMachine($machineSlug, $fieldMapData, $configs)
    {
        switch ($machineSlug) {
            case 'createMeeting':
                return $this->googleMeetService->createMeeting($fieldMapData, $configs['calendar-id']['value']);
        }
    }

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

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

        $headers = [
            'Content-Type'  => 'application/json',
            'Authorization' => $accessToken,
        ];

        $this->googleMeetService = new GoogleMeetService($headers);

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