<?php

namespace BitApps\PiPro\src\Integrations\Klaviyo;

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 KlaviyoAction implements ActionInterface
{
    private NodeInfoProvider $nodeInfoProvider;

    private KlaviyoService $klaviyoService;

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

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

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

    private function executeMachine($machineSlug, $fieldMapData, $configs, $profileIdList, $locationList, $propertiesList)
    {
        switch ($machineSlug) {
            case 'createProfile':
                $fieldMapData['data']['type'] = 'profile';

                if (!empty($locationList)) {
                    $fieldMapData['data']['attributes']['location'] = $locationList;
                }
                if (!empty($propertiesList)) {
                    $fieldMapData['data']['attributes']['properties'] = $propertiesList;
                }

                return $this->klaviyoService->createProfile($fieldMapData, $configs['add-to-list']['value'], $configs['list-id']['value']);

            case 'createList':
                $fieldMapData['data']['type'] = 'list';

                return $this->klaviyoService->createList($fieldMapData);

            case 'createEvent':
                $fieldMapData['data']['type'] = 'event';

                if (!empty($propertiesList)) {
                    $fieldMapData['data']['attributes']['properties'] = $propertiesList;
                }

                $fieldMapData['data']['attributes']['metric']['data']['type'] = 'metric';
                $fieldMapData['data']['attributes']['profile']['data']['type'] = 'profile';
                $attributeValue = $fieldMapData['data']['attributes']['value'];

                if (isset($attributeValue)) {
                    $fieldMapData['data']['attributes']['value'] = (float) $attributeValue;
                }

                return $this->klaviyoService->createEvent($fieldMapData);

            case 'updateList':
                $fieldMapData['data']['type'] = 'list';
                $listId = $fieldMapData['data']['id'];

                return $this->klaviyoService->updateList($fieldMapData, $listId);

            case 'addProfilesToList':
                $listId = $fieldMapData['data']['id'];

                return $this->klaviyoService->addProfileToList($profileIdList, $listId);
        }
    }

    private function executeKlaviyoAction()
    {
        $machineSlug = $this->nodeInfoProvider->getMachineSlug();
        $configs = $this->nodeInfoProvider->getFieldMapConfigs();
        $fieldMapData = $this->nodeInfoProvider->getFieldMapData();
        $profileIdList = $this->nodeInfoProvider->getFieldMapRepeaters('profile-id-list.value', false, false);
        $locationList = $this->nodeInfoProvider->getFieldMapRepeaters('location-list.value', false, true, 'klaviyoFields');
        $propertiesList = $this->nodeInfoProvider->getFieldMapRepeaters('properties-list.value', false, true);

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

        $headers = [
            'Content-Type'  => 'application/json',
            'Authorization' => 'Klaviyo-API-Key ' . $apiKey,
            'revision'      => '2025-07-15'
        ];

        $this->klaviyoService = new KlaviyoService($headers);

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