<?php

namespace BitApps\PiPro\src\Integrations\MicrosoftExcel;

// 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;
use BitApps\PiPro\Deps\BitApps\WPKit\Http\Client\HttpClient;
use InvalidArgumentException;

class MicrosoftExcelAction implements ActionInterface
{
    private NodeInfoProvider $nodeInfoProvider;

    private MicrosoftExcelService $excelService;

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

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

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

    private function executeMachine($machineSlug, $configs, $fieldMapData)
    {
        $workbookId = $configs['workbook-id']['value'] ?? null;
        $worksheetId = $configs['worksheet-id']['value'] ?? null;


        switch ($machineSlug) {
            case 'addWorksheetToWorkbook':
                return $this->excelService->addWorksheetToWorkbook($workbookId, $fieldMapData);

            case 'createTable':
                $selectRange = $configs['select-range']['value'];

                return $this->excelService->createTable($workbookId, $worksheetId, $selectRange, $fieldMapData);

            case 'deleteTable':
                $tableId = $configs['table-id']['value'];

                return $this->excelService->deleteTable($workbookId, $worksheetId, $tableId);

            case 'deleteWorksheet':
                return $this->excelService->deleteWorksheet($workbookId, $worksheetId);

            case 'clearWorksheet':
                $range = $configs['range']['value'] ?? false;

                return $this->excelService->clearWorksheet($workbookId, $worksheetId, $fieldMapData, $range);

            case 'listWorksheetRows':
                $range = $fieldMapData['targetRange'] ?? '';

                return $this->excelService->listWorksheetRows($workbookId, $worksheetId, $range);

            case 'addWorksheetRow':
                $rowsData = $this->nodeInfoProvider->getFieldMapRepeaters('rows-data.value', false, true, 'column');

                return $this->excelService->addWorksheetRow($workbookId, $worksheetId, $rowsData);

            case 'updateWorksheetRow':
                $rowsData = $this->nodeInfoProvider->getFieldMapRepeaters('rows-data.value', false, true, 'column');

                return $this->excelService->updateWorksheetRow($workbookId, $worksheetId, $fieldMapData, $rowsData);

            case 'getAllWorksheets':
                $returnAll = $configs['return-all']['value'];

                return $this->excelService->getAllWorksheets($workbookId, $returnAll, $fieldMapData);

            default:
                throw new InvalidArgumentException("Unknown action: {$machineSlug}");
        }
    }

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


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

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

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