<?php declare(strict_types=1);

namespace Newland\Toubiz\Poi\Neos\Service;

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Configuration\ConfigurationManager;
use Newland\NeosCommon\Service\ConfigurationService;

/**
 * @Flow\Scope("singleton")
 */
class OutdoorActiveCredentialsService
{

    /**
     * @var ConfigurationService
     * @Flow\Inject()
     */
    protected $configurationService;

    /**
     * @var ConfigurationManager
     * @Flow\Inject()
     */
    protected $configurationManager;

    public function getOutdoorActiveConfiguration(NodeInterface $node): ?array
    {
        // Get configuration from POI settings.
        $siteConfiguration = $this->configurationService->getCurrentSiteConfiguration(
            $node,
            'Newland.Toubiz.Poi.Neos.outdoorActiveConfigurations'
        );
        if ($siteConfiguration) {
            return $siteConfiguration;
        }

        $serviceConfiguration = $this->configurationManager->getConfiguration(
            ConfigurationManager::CONFIGURATION_TYPE_SETTINGS,
            'Newland.Toubiz.Sync.Neos.services'
        );
        $outdoorActiveConfiguration = $serviceConfiguration['OutdoorActive/Api']
            ?? $serviceConfiguration['Outdooractive/Api']
            ?? null;

        if (!\is_array($outdoorActiveConfiguration)) {
            return null;
        }

        // Search for a 'Default' or 'default' Sync setting
        $defaultConfig = $outdoorActiveConfiguration['clients']['Default']
            ?? $outdoorActiveConfiguration['clients']['default']
            ?? null;
        if ($defaultConfig) {
            return $defaultConfig;
        }

        // Fallback to first declared configuration.
        return reset($outdoorActiveConfiguration['clients']);
    }
}
