<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Monitoring\Error;

use CpCreation\VitiCore\Commerce\Catalog\Configuration\CatalogConfigurationProvider;
use CpCreation\VitiCore\Commerce\Catalog\Configuration\CatalogHubConfiguration;
use CpCreation\VitiCore\Commerce\Catalog\Configuration\CatalogIntegrationConfiguration;

final readonly class ErrorMonitoringConfiguration
{
    public function __construct(
        private CatalogIntegrationConfiguration $integrationConfiguration,
        private CatalogHubConfiguration $hubConfiguration,
        private CatalogConfigurationProvider $configurationProvider,
    ) {
    }

    public function isReady(): bool
    {
        $snapshot = $this->configurationProvider->current();

        return true === $snapshot?->monitoringEnabled
            && $this->integrationConfiguration->hasValidInstanceId()
            && $this->hubConfiguration->hasHubUrl()
            && '' !== mb_trim($snapshot->webhookUrl ?? '')
            && mb_strlen($snapshot->webhookSecret ?? '', '8bit') >= 32;
    }

    public function instanceId(): string
    {
        if (!$this->isReady()) {
            throw new \LogicException('Le monitoring des erreurs vers le hub n’est pas configuré.');
        }

        return $this->integrationConfiguration->instanceId();
    }

    public function endpointUrl(string $resource = 'errors'): string
    {
        return $this->hubConfiguration->hubUrl()
            .'/api/integrations/serenity/'
            .rawurlencode($this->instanceId())
            .'/'
            .rawurlencode($resource);
    }

    public function secret(): string
    {
        if (!$this->isReady()) {
            throw new \LogicException('Le secret du monitoring des erreurs vers le hub n’est pas configuré.');
        }

        return (string) $this->configurationProvider->current()?->webhookSecret;
    }
}
