<?php declare(strict_types=1);

namespace Newland\Toubiz\Poi\Neos\Service;

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

/**
 * @Flow\Scope("singleton")
 */
class OutdoorActiveCredentialsService
{
    /**
     * The configuration for the sync package.
     *
     * @Flow\InjectConfiguration(package="Newland.Toubiz.Sync.Neos", path="services")
     * @var array
     */
    protected $serviceConfiguration;

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

    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;
        }

        $outdoorActiveConfiguration = $this->serviceConfiguration['OutdoorActive/Api']
            ?? $this->serviceConfiguration['Outdooractive/Api']
            ?? null;

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

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

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