<?php
/*
 * package examples/crash_reporter/backend/public/api/upload.php
 * upload.php
 * Created at: Wed 20 May 2026 14:31:55 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 25 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	edbab2563cb9d5ba1c9a6a6272071ac12efa782274c7d1626f088a951033d5a6
 */
declare(strict_types=1);
require_once __DIR__ . '/../../src/bootstrap.php';

$raw = read_crash_upload_body();
if ($raw === null) {
    json_out(['ok' => false, 'error' => 'empty body'], 400);
}
if ($raw === false) {
    json_out(['ok' => false, 'error' => 'invalid gzip body'], 400);
}
$data = json_decode($raw, true);
if (!is_array($data)) {
    json_out(['ok' => false, 'error' => 'invalid json'], 400);
}
if ((int) ($data['schema_version'] ?? 0) !== 1) {
    json_out(['ok' => false, 'error' => 'unsupported schema_version'], 400);
}
try {
    ReportRepository::insert($data);
    json_out(['ok' => true, 'report_id' => $data['report_id'] ?? null]);
} catch (PDOException $e) {
    $msg = $e->getMessage();
    if ($e->getCode() === '23000' || stripos($msg, 'UNIQUE') !== false) {
        json_out(['ok' => false, 'error' => 'duplicate report_id'], 409);
    }
    error_log('crash upload PDO: ' . $msg);
    log_crash_event('upload', 'PDO: ' . $msg);
    $out = ['ok' => false, 'error' => 'store failed'];
    if (cfg('debug')) {
        $out['hint'] = $msg;
    }
    json_out($out, 500);
} catch (Throwable $e) {
    error_log('crash upload: ' . $e->getMessage());
    log_crash_event('upload', $e->getMessage());
    $out = ['ok' => false, 'error' => 'store failed'];
    if (cfg('debug')) {
        $out['hint'] = $e->getMessage();
    }
    json_out($out, 500);
}
