<?php

namespace KupShop\ComponentsBundle\Twig\Components\Utils;

use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\KupShopBundle\Util\System\TransactionUtl;
use KupShop\KupShopBundle\Util\System\UrlFinder;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Components/components/Utils/Sentry/Sentry.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null, newCss: null),
])]
class Sentry extends BaseComponent
{
    public $smartyFallback = false;

    public function __construct(private readonly UrlFinder $urlFinder, private readonly TransactionUtl $transactionUtl)
    {
    }

    public function getSentryMonitoring(): string
    {
        return \Settings::getDefault()->sentry_monitoring ?? 'N';
    }

    public function shopUrls(): array
    {
        return array_filter([
            $this->regexEscapeUrl($this->urlFinder->shopUrlAbsolute('')),
            $this->urlFinder->hasCDN() ? $this->regexEscapeUrl($this->urlFinder->staticUrl('')) : null,
        ]);
    }

    public function getShopName(): string
    {
        return getenv('BRANCH') ? substr(getenv('BRANCH'), 5) : 'local';
    }

    public function isAdminUser(): int
    {
        return getAdminUser() ? 1 : 0;
    }

    public function getTransaction()
    {
        $transaction = $this->transactionUtl->getRequestStack()->getCurrentRequest()->attributes->get('wpj_transaction');

        if (is_array($transaction)) {
            return join('|', $transaction);
        }

        return $transaction;
    }

    private function regexEscapeUrl(string $url): string
    {
        return str_replace(['.', '/'], ['\.', '\/'], $url);
    }

    public function getSentryInitJson(): string
    {
        return json_encode([
            'shopName' => $this->getShopName(),
            'shopUrls' => $this->shopUrls(),
            'transaction' => $this->getTransaction(),
            'isAdminUser' => $this->isAdminUser(),
            'monitoring' => true,
            'smartyFallback' => $this->smartyFallback,
        ]);
    }
}
