<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/api/v1/device-probes/cookie')]
final class DeviceProbeController
{
    private const COOKIE = '__Host-device_probe';

    public function __construct(private readonly bool $deviceProbesEnabled)
    {
    }

    #[Route('', name: 'api_device_probe_cookie_set', methods: ['POST'])]
    public function set(): JsonResponse
    {
        if (!$this->deviceProbesEnabled) {
            return new JsonResponse(['error' => 'not_found'], 404);
        }

        $response = new JsonResponse(['stored' => true], Response::HTTP_CREATED);
        $response->headers->setCookie(Cookie::create(self::COOKIE)
            ->withValue(bin2hex(random_bytes(16)))
            ->withExpires(new \DateTimeImmutable('+10 minutes'))
            ->withPath('/')
            ->withSecure(true)
            ->withHttpOnly(true)
            ->withSameSite(Cookie::SAMESITE_STRICT));

        return $response;
    }

    #[Route('', name: 'api_device_probe_cookie_check', methods: ['GET'])]
    public function check(Request $request): JsonResponse
    {
        if (!$this->deviceProbesEnabled) {
            return new JsonResponse(['error' => 'not_found'], 404);
        }

        return new JsonResponse(['stored' => $request->cookies->has(self::COOKIE)]);
    }

    #[Route('', name: 'api_device_probe_cookie_delete', methods: ['DELETE'])]
    public function delete(): JsonResponse
    {
        if (!$this->deviceProbesEnabled) {
            return new JsonResponse(['error' => 'not_found'], 404);
        }

        $response = new JsonResponse(null, Response::HTTP_NO_CONTENT);
        $response->headers->clearCookie(self::COOKIE, '/', null, true, true, Cookie::SAMESITE_STRICT);

        return $response;
    }
}
