<?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\Bridge\Symfony\Bundle\Tracking;

use CpCreation\VitiCore\Shop\Model\ShopConfig;
use CpCreation\VitiCore\Shop\Repository\ShopConfigRepository;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

#[AsMessageHandler]
final readonly class ServerTrackingMessageHandler
{
    private const string GRAPH_API_VERSION = 'v23.0';

    public function __construct(
        private ShopConfigRepository $shopConfigRepository,
        private HttpClientInterface $httpClient,
        private string $matomoAuthToken = '',
        private ?LoggerInterface $logger = null,
    ) {
    }

    public function __invoke(ServerTrackingMessage $message): void
    {
        $config = $this->shopConfigRepository->findOne();

        if (!$config instanceof ShopConfig) {
            return;
        }

        match ($message->provider) {
            ServerTrackingMessage::PROVIDER_MATOMO => $this->sendMatomo($config, $message),
            ServerTrackingMessage::PROVIDER_META => $this->sendMeta($config, $message),
            default => $this->logger?->warning('Unknown server tracking provider.', [
                'provider' => $message->provider,
            ] + $message->context),
        };
    }

    private function sendMatomo(ShopConfig $config, ServerTrackingMessage $message): void
    {
        if (!$config->isMatomoConfigured() || !$config->isEnableMatomoEcommerceTracking()) {
            return;
        }

        try {
            $body = array_filter($message->payload, static fn (mixed $value): bool => null !== $value && '' !== $value);
            $matomoAuthToken = mb_trim($this->matomoAuthToken);

            if ('' !== $matomoAuthToken) {
                $body['token_auth'] = $matomoAuthToken;
            }

            $response = $this->httpClient->request('POST', rtrim((string) $config->getMatomoTrackingServerUrl(), '/').'/matomo.php', [
                'body' => $body,
                'timeout' => 3,
            ]);

            $statusCode = $response->getStatusCode();
            if ($statusCode >= 400) {
                $this->logger?->warning('Matomo ecommerce tracking failed.', [
                    'status_code' => $statusCode,
                ] + $message->context);
            }
        } catch (TransportExceptionInterface $exception) {
            $this->logger?->warning('Matomo ecommerce tracking failed.', [
                'exception' => $exception,
            ] + $message->context);
        }
    }

    private function sendMeta(ShopConfig $config, ServerTrackingMessage $message): void
    {
        if (!$config->isMetaConversionsApiConfigured()) {
            return;
        }

        foreach ($config->getMetaConversionsPixelConfigs() as $pixelConfig) {
            $payload = $message->payload;
            $payload['access_token'] = $pixelConfig['accessToken'];

            if (null !== $config->getMetaTestEventCode()) {
                $payload['test_event_code'] = $config->getMetaTestEventCode();
            }

            $this->sendMetaPixelEvent($pixelConfig['pixelId'], $payload, $message->context);
        }
    }

    /**
     * @param array<string, mixed> $payload
     * @param array<string, mixed> $context
     */
    private function sendMetaPixelEvent(string $pixelId, array $payload, array $context = []): void
    {
        try {
            $response = $this->httpClient->request(
                'POST',
                sprintf('https://graph.facebook.com/%s/%s/events', self::GRAPH_API_VERSION, rawurlencode($pixelId)),
                [
                    'json' => $payload,
                    'timeout' => 3,
                ],
            );

            $statusCode = $response->getStatusCode();
            if ($statusCode >= 400) {
                $this->logger?->warning('Meta Conversions API tracking failed.', [
                    'pixel_id' => $pixelId,
                    'status_code' => $statusCode,
                ] + $context);
            }
        } catch (TransportExceptionInterface $exception) {
            $this->logger?->warning('Meta Conversions API tracking failed.', [
                'pixel_id' => $pixelId,
                'exception' => $exception,
            ] + $context);
        }
    }
}
