<?php

declare(strict_types=1);

use Ideals\MarketingService\AllowedOrigins;
use Ideals\MarketingService\Cors;
use Ideals\MarketingService\Uuid;

require __DIR__.'/../vendor/autoload.php';

const COOKIE_NAME = 'user_uuid';
const COOKIE_TTL = 60 * 60 * 24 * 365; // 1 year

header('Vary: Origin');
header('X-Content-Type-Options: nosniff');

$cors = new Cors(AllowedOrigins::get());
$origin = $_SERVER['HTTP_ORIGIN'] ?? null;

if (!is_string($origin) || !$cors->isAllowed($origin)) {
    http_response_code(403);
    exit;
}

$cors->sendHeaders($origin);
header('Content-Type: application/json');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

$method = $_SERVER['REQUEST_METHOD'] ?? '';

if ('OPTIONS' === $method) {
    $cors->sendPreflightHeaders();
    http_response_code(204);
    exit;
}

if ('GET' !== $method) {
    header('Allow: '.$cors->allowedMethods());
    http_response_code(405);
    exit;
}

$uuid = Uuid::generate($_COOKIE[COOKIE_NAME] ?? null);

try {
    $body = json_encode(['uuid' => $uuid], \JSON_THROW_ON_ERROR);
} catch (JsonException) {
    http_response_code(500);
    echo '{"error":"Internal Server Error"}';
    exit;
}

// Re-sent on every request so the expiry slides forward for active users.
setcookie(COOKIE_NAME, $uuid, [
    'expires' => time() + COOKIE_TTL,
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'None',
]);

echo $body;
