<?php

declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
header('X-Content-Type-Options: nosniff');

if (strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'GET') {
    http_response_code(405);
    header('Allow: GET');
    echo json_encode(['success' => false, 'error' => 'method_not_allowed']);
    return;
}

try {
    $issued = myronPublicInteractionTokenService()->issue(
        (string) ($_GET['purpose'] ?? ''),
        (string) ($_GET['resource'] ?? '')
    );
    echo json_encode(['success' => true] + $issued, JSON_UNESCAPED_SLASHES);
} catch (InvalidArgumentException $exception) {
    http_response_code(422);
    echo json_encode(['success' => false, 'error' => 'input_invalid', 'message' => $exception->getMessage()]);
} catch (Throwable) {
    http_response_code(503);
    echo json_encode(['success' => false, 'error' => 'token_unavailable']);
}
