<?php

use MintyPHP\Http\RequestContext;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Audit\FrontendTelemetryIngestService;
use MintyPHP\Session;

if ((requestInput()->method()) !== 'POST') {
    http_response_code(405);
    Router::json(['ok' => false, 'error' => 'method_not_allowed']);
    return;
}

$sessionStore = app(SessionStoreInterface::class);
$session = $sessionStore->all();
$currentUserId = (int) ($session['user']['id'] ?? 0);
if ($currentUserId <= 0) {
    http_response_code(403);
    Router::json(['ok' => false, 'error' => 'forbidden']);
    return;
}

if (!Session::checkCsrfToken()) {
    http_response_code(403);
    Router::json(['ok' => false, 'error' => 'csrf']);
    return;
}

$body = requestInput()->bodyAll();
if (!is_array($body)) {
    http_response_code(204);
    return;
}

$allowedKeys = ['event_type', 'severity', 'message', 'fingerprint', 'meta', 'occurred_at'];
$csrfKey = Session::$csrfSessionKey;
foreach ($body as $key => $value) {
    if (!is_string($key)) {
        continue;
    }

    if ($key === $csrfKey) {
        continue;
    }

    if (!in_array($key, $allowedKeys, true)) {
        http_response_code(204);
        return;
    }
}

$payload = [];
foreach ($allowedKeys as $key) {
    if (!array_key_exists($key, $body)) {
        continue;
    }
    $payload[$key] = $body[$key];
}

$eventType = $payload['event_type'] ?? null;
$severity = $payload['severity'] ?? null;
$message = $payload['message'] ?? null;
$fingerprint = $payload['fingerprint'] ?? null;
$meta = $payload['meta'] ?? null;
$occurredAt = $payload['occurred_at'] ?? null;

if (($eventType !== null && is_array($eventType))
    || ($severity !== null && is_array($severity))
    || ($message !== null && is_array($message))
    || ($fingerprint !== null && is_array($fingerprint))
    || ($occurredAt !== null && is_array($occurredAt))
    || ($meta !== null && !is_array($meta) && !is_string($meta))
) {
    http_response_code(204);
    return;
}

$eventTypeLength = strlen((string) $eventType);
$severityLength = strlen((string) $severity);
$messageLength = strlen((string) $message);
$fingerprintLength = strlen((string) $fingerprint);
$occurredAtLength = strlen((string) $occurredAt);
$metaLength = is_string($meta) ? strlen($meta) : 0;

if ($eventTypeLength > 64
    || $severityLength > 16
    || $messageLength > 1000
    || $fingerprintLength > 256
    || $occurredAtLength > 64
    || $metaLength > 2048
) {
    http_response_code(204);
    return;
}

$payloadSize = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (is_string($payloadSize) && strlen($payloadSize) > 4096) {
    http_response_code(204);
    return;
}

$result = app(FrontendTelemetryIngestService::class)->ingest($payload);
if (!(bool) ($result['accepted'] ?? false) && (string) ($result['reason'] ?? '') === 'record_failed') {
    error_log('[frontend-telemetry] ingest record_failed request_id=' . RequestContext::id());
}
http_response_code(204);
