<?php

namespace BitApps\PiPro\src\Integrations\Zoom;

// Prevent direct script access
if (!\defined('ABSPATH')) {
    exit;
}

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;

class ZoomAction implements ActionInterface
{
    private NodeInfoProvider $nodeInfoProvider;

    private ZoomService $zoomService;

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

    public function execute(): array
    {
        $result = $this->executeZoomAction();

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

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

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

        $header = [
            'Content-Type'  => 'application/json; charset=utf-8',
            'Authorization' => $accessToken,
        ];

        return [
            'machineSlug'  => $machineSlug,
            'configs'      => $configs,
            'fieldMapData' => $fieldMapData,
            'header'       => $header,
        ];
    }

    private function executeAction(array $data)
    {
        switch ($data['machineSlug']) {
            case 'createMeeting':
                return $this->zoomService->createMeeting($data['fieldMapData']);

            case 'getMeeting':
                return $this->zoomService->getMeeting($data['fieldMapData']['meeting']);

            case 'getManyMeetings':
                return $this->zoomService->getManyMeetings($data['fieldMapData']);

            case 'updateMeeting':
                return $this->zoomService->updateMeeting($data['fieldMapData']);


            case 'deleteMeeting':
                return $this->zoomService->deleteMeeting($data['fieldMapData']['meeting'], $data['fieldMapData']['occurrenceId'], $data['fieldMapData']['scheduleReminder']);

            case 'createWebinar':
                return $this->zoomService->createWebinar($data['fieldMapData']);

            case 'sendChatMessage':
                return $this->zoomService->sendChatMessage($data['fieldMapData'], $data['configs']['targetType']['value']);
        }
    }

    private function executeZoomAction(): array
    {
        $data = $this->prepareRequestContext();
        $this->zoomService = new ZoomService($data['header']);

        return $this->executeAction($data);
    }
}
