<?php

namespace App\Shared\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class SecurityHeadersSubscriber implements EventSubscriberInterface
{
    public function onKernelResponse(ResponseEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $response = $event->getResponse();
        $response->headers->set('X-Content-Type-Options', 'nosniff');
        $response->headers->set('X-Frame-Options', 'DENY');
        $response->headers->set('X-XSS-Protection', '1; mode=block');
        $response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
        $response->headers->set('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');

        if ($event->getRequest()->isSecure()) {
            $response->headers->set('Strict-Transport-Security', 'max-age=63072000; includeSubDomains');
        }

        $path = $event->getRequest()->getPathInfo();
        if (str_starts_with($path, '/api') && !str_starts_with($path, '/api/doc')) {
            // صفحات مرورگرمحورِ پرداخت (order/pay/callback) HTML برمی‌گردانند و به
            // inline style + فونت + فرمِ انتقال به شاپرک نیاز دارند؛ بقیهٔ API (JSON)
            // همان سیاست سخت‌گیرانه را می‌گیرد.
            $isPaymentPage =
                str_starts_with($path, '/api/v1/payment/order/')
                || str_starts_with($path, '/api/v1/payment/pay/')
                || str_starts_with($path, '/api/v1/payment/callback/')
                || str_starts_with($path, '/api/v1/subscription-payment/callback/');

            $response->headers->set(
                'Content-Security-Policy',
                $isPaymentPage
                    ? "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; "
                        . "font-src https://cdn.jsdelivr.net data:; img-src data:; "
                        . "form-action https://*.shaparak.ir https://sandbox.banktest.ir; base-uri 'none'"
                    : "default-src 'none'"
            );
        }

        if (str_starts_with($path, '/admin') || str_starts_with($path, '/api')) {
            $response->headers->set('X-Robots-Tag', 'noindex, nofollow');
        }
    }

    public static function getSubscribedEvents(): array
    {
        return [KernelEvents::RESPONSE => 'onKernelResponse'];
    }
}
