<?php

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

#[AsEventListener(event: KernelEvents::REQUEST, priority: 64)]
final class DeviceRequestGuardSubscriber
{
    public function __construct(private readonly string $publicUrl)
    {
    }

    public function __invoke(RequestEvent $event): void
    {
        $request = $event->getRequest();
        $path = $request->getPathInfo();

        if (!$this->isDeviceMutation($request, $path)) {
            return;
        }

        $expectedOrigin = rtrim($this->publicUrl, '/');
        $origin = rtrim((string) $request->headers->get('Origin'), '/');
        $marker = $request->headers->get('X-Family-Connect-Request');

        if ($expectedOrigin !== $origin || 'device' !== $marker) {
            $event->setResponse(new JsonResponse(['error' => 'invalid_device_request_origin'], 403));
        }
    }

    private function isDeviceMutation(Request $request, string $path): bool
    {
        if (in_array($request->getMethod(), ['GET', 'HEAD'], true)) {
            return false;
        }

        return str_starts_with($path, '/api/v1/device/')
            || str_starts_with($path, '/api/v1/device-pairings/')
            || str_starts_with($path, '/api/v1/device-probes/');
    }
}
