<?php

declare(strict_types=1);

/*
 * 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\Commerce\Catalog\Configuration;

final readonly class CatalogWebhookEndpointResolver
{
    public function __construct(
        private CatalogIntegrationConfiguration $catalogConfiguration,
        private CatalogHubConfiguration $hubConfiguration,
        private string $explicitWebhookUrl,
        #[\SensitiveParameter]
        private string $webhookSecret,
        private ?CatalogConfigurationProvider $configurationProvider = null,
    ) {}

    public function isReady(): bool
    {
        return $this->catalogConfiguration->isEnabled() && $this->isHubConnectionReady();
    }

    public function isHubConnectionReady(): bool
    {
        if (!$this->catalogConfiguration->isHubConnectionEnabled()
            || !$this->catalogConfiguration->hasValidInstanceId()
            || mb_strlen($this->resolvedSecret()) < 32
        ) {
            return false;
        }

        $url = $this->resolvedUrl();

        return null !== $url && CatalogHubConfiguration::isAllowedAbsoluteUrl(
            $url,
            $this->hubConfiguration->allowsInsecureTransport(),
        );
    }

    public function url(): string
    {
        if (!$this->isHubConnectionReady()) {
            throw new \LogicException('The VitiCore Commerce webhook endpoint is not configured.');
        }

        return (string) $this->resolvedUrl();
    }

    public function secret(): string
    {
        if (!$this->isHubConnectionReady()) {
            throw new \LogicException('The VitiCore Commerce webhook secret is not configured.');
        }

        return $this->resolvedSecret();
    }

    private function resolvedUrl(): ?string
    {
        if ($this->configurationProvider instanceof CatalogConfigurationProvider) {
            $snapshot = $this->configurationProvider->current();
            $webhookUrl = mb_trim($snapshot?->webhookUrl ?? '');
            if ('' !== $webhookUrl) {
                return $webhookUrl;
            }

            if (null === $snapshot || !$this->hubConfiguration->hasHubUrl()) {
                return null;
            }

            return $this->hubConfiguration->hubUrl()
                . '/webhooks/serenity/by-instance/'
                . rawurlencode($this->catalogConfiguration->instanceId());
        }

        $explicitWebhookUrl = mb_trim($this->explicitWebhookUrl);
        if ('' !== $explicitWebhookUrl) {
            return $explicitWebhookUrl;
        }

        if (!$this->hubConfiguration->hasHubUrl()) {
            return null;
        }

        return $this->hubConfiguration->hubUrl()
            . '/webhooks/serenity/by-instance/'
            . rawurlencode($this->catalogConfiguration->instanceId());
    }

    private function resolvedSecret(): string
    {
        if ($this->configurationProvider instanceof CatalogConfigurationProvider) {
            return $this->configurationProvider->current()?->webhookSecret ?? '';
        }

        return $this->webhookSecret;
    }
}
